package com.handinfo.engine;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

import android.util.Log;

import com.handinfo.engine.net.BaseConnection;
import com.handinfo.engine.net.ConnectionHandler;
import com.handinfo.engine.net.GameProtocol;
import com.handinfo.engine.net.HttpConnect;
import com.handinfo.engine.net.TcpConnection;
import com.handinfo.engine.resource.ObjectAdapter;
import com.handinfo.engine.resource.ResHead;
import com.handinfo.engine.resource.Resource;
import com.handinfo.engine.resource.ResourceList;
import com.handinfo.engine.resource.ResourceManager;
import com.handinfo.engine.resource.Serializeable;
import com.handinfo.game.AbstractGameActor;
import com.handinfo.game.ActorItem;
import com.handinfo.game.ActorItemEquip;
import com.handinfo.game.ActorRole;
import com.handinfo.game.ChatItem;
import com.handinfo.game.GameMessage;
import com.handinfo.game.GameScene;
import com.handinfo.game.GameScreen;
import com.handinfo.game.LoadingScreen;
import com.handinfo.game.RoleCombatSkill;
import com.handinfo.game.UserScreen;
import com.handinfo.uimenu.AbsHyperLinker;
import com.handinfo.uimenu.UIListener;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UIMessageBox;
import com.handinfo.uimenu.UITools;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.uimenu.window.UIFamilyWindow;
import com.handinfo.uimenu.window.UILifeSkillsWindow;
import com.handinfo.uimenu.window.UIMain;
import com.handinfo.uimenu.window.UINPCWindow;
import com.handinfo.uimenu.window.UIShowData;
import com.handinfo.uimenu.window.UITaskWindow;
import com.handinfo.util.ArrayList;
import com.handinfo.util.TextBox;
import com.handinfo.util.Tools;

//#if edition == "JIUYOU" || edition == "JIUYOU_1" || edition == "JIUYOU_2" || edition == "JIUYOU_3" || edition == "JIUYOU_4"|| edition == "JIUYOU_5" || edition == "JIUYOU_6"
//# import com.uc.gsdk.javame.api.UCGameSdk;
//# import com.uc.gsdk.javame.api.UCLogLevel;
//# import com.uc.gsdk.javame.api.UCSdkEvent;
//# import com.uc.gsdk.javame.api.UCSdkListener;
//#endif

/**
 *
 * @author Xia Mingwei
 * @version 1.0
 */
public class GameManager implements Runnable, ConnectionHandler
{
	private static GameManager s_instance;
	public AbstractGameScreen m_screen; // 游戏画布
	public UserScreen m_user_screen;// 登录
	public GameMessage m_game_message;// 消息发送管理
	public LoadingScreen m_loading_screen;// loaogoding

	//#if edition == "JIUYOU"|| edition == "JIUYOU_1" || edition == "JIUYOU_2" || edition == "JIUYOU_3" || edition == "JIUYOU_4"|| edition == "JIUYOU_5" || edition == "JIUYOU_6"
	//# public UCGameSdk m_uc_sdk = null;//56925
	//# public String m_uc_msg = null;
	//# public boolean m_uc_inited = false;
	//# public String m_uc_sid = null;
	//#endif

//	public UCGameSdk m_uc_sdk = null;//56925
//	public String m_uc_msg = null;
//	public boolean m_uc_inited = false;
//	public String m_uc_sid = null;

	public int m_waitingCommandId = -1; // 某些指令发送后，客户端处于等待状态
	// //场景相关
	public AbstractGameScene m_scene; // 游戏场景
	public String m_stage = null;// 场景ID
	public String m_map_name = null;// 地图名字
	public byte m_areaType;//地图区域类型 0战斗区 1安全区
	public ResourceList m_sceneResList = new ResourceList(); // 场景资源列表
	//public ResourceList m_roleResList = new ResourceList(); // 玩家角色资源列表
	// //影子
	public ResourceList m_shadowResList = new ResourceList();// 缺省状态影子角色资源列表
	public Animation m_shadowAnimation = new Animation();

	public ResHead m_sceneResHead = new ResHead();
	public ActorRole m_role = null;// 自己
	public int m_role_x;
	public int m_role_y;

	public Vector m_social_list = new Vector();// 社交界面数组
	public long m_social_role_id = 0;// 社交系统中正在操作的玩家ID
	public static final byte SOCIAL_TYPE_FRIEND = 0;// 好友
	public static final byte SOCIAL_TYPE_BLACKLIST = 1;// 黑名单
	public static final byte SOCIAL_TYPE_ENEMY = 2;// 仇敌

	public ArrayList m_team_list = new ArrayList(); // 队伍数组
	public static final byte TEAM_TYPE_TROOPS = 0; // 队伍
	public static final byte TEAM_TYPE_NEARBYROOPS = 1; // 附近队伍

	public Image[] img_head_status = null;// NPC头上图标

	public Image img_softkey = null;// 左右软件
	public Image img_corner = null;// 左右软件替换角
	public Image img_select = null;// 选择框的左右角
	public Image img_time_bar_left = null;// 计时条 左边
	public Image img_time_bar_right = null;// 计时条 右边
	public Image img_page_corner = null;// 左右翻页的角
	public Image img_casting_bar = null;// 施法条

	// 寻路
	// public ArrayList m_pathfinding_point = null;// 寻路终点集合
	// public int m_pathfinding_label = 0;// 寻路终点索引
	// public boolean m_pathfinding_pause = false;// 是否暂停
	// public boolean m_pathfinding_start = false;// 是否在寻路
	// public short[] m_pathfinding_paths = null;// 寻路的路径集合
	// public int m_pathfinding_index = 0;
	// public long m_pathfinding_id = 0;// 寻路的目标ID
	// //跟随
	// public ArrayList m_followTarget_point = null;// 跟随终点集合
	// public boolean m_followTarget = false; //是否开始跟随
	// public short[] m_followTarget_paths = null;// 跟随的路径集合
	// public int m_followTarget_index = 0;
	// public long m_followTarget_id = 0;// 跟随的目标ID
	// public boolean m_follow_isArriveTarget = false;

	public static final int COLOR_ACTOR_SHADOW = 0xaa473b34;

	// 进度条相关 2011.11.06 xujianping//
	public static final int COLOR_LOADINGBAR = 0x2cc8d9; // 进度加载的颜色
	//

	/** 用户ID */
	public long m_userID = 0;

	public byte m_permission = 0;// 客户端权限
	public int m_server_id = 0;// 服务器ID
	public String m_server_name = null;// 当前服务器名字

	public boolean m_is_autopath = false;//是否为自动寻路切图
	// /** 角色ID */
	// public int m_actorID = 0;

	// 是否由Ui控制
	public static boolean s_isControlledByUi;

	public Image img_lock_network = null;
	public static final String URL_IMG_LOCK_NETWORK = "/login/bagua.png";

	// 24人物形象对应表
	public static final String[][][] s_roleModemList = { { { "m_x_jk_1",// 男剑仙
			"m_y_jk_1",// 男剑妖
			"m_r_jk_1",// 男剑人
			"m_g_jk_1",// 男剑鬼
	}, { "m_x_dk_1",// 男武仙
			"m_y_dk_1",// 男武妖
			"m_r_dk_1",// 男武人
			"m_g_dk_1",// 男武鬼
	}, { "m_x_fs_1",// 男道仙
			"m_y_fs_1",// 男道妖
			"m_r_fs_1",// 男道人
			"m_g_fs_1",// 男道鬼
	} }, { { "f_x_jk_1",// 女剑仙
			"f_y_jk_1",// 女剑妖
			"f_r_jk_1",// 女剑人
			"f_g_jk_1",// 女剑鬼
	}, { "f_x_dk_1",// 女武仙
			"f_y_dk_1",// 女武妖
			"f_r_dk_1",// 女武人
			"f_g_dk_1",// 女武鬼
	}, { "f_x_fs_1",// 女道仙
			"f_y_fs_1",// 女道妖
			"f_r_fs_1",// 女道人
			"f_g_fs_1",// 女道鬼
	} } };

	private GameManager()
	{
		m_resource_scene = new Resource();
		m_resource_static = new Resource();
		// m_resource_dynamic = new Resource();
	}

	public static GameManager createGameManager(AbstractGameScreen screen)
	{
		s_instance = new GameManager();
		s_instance.m_screen = screen;
		s_instance.m_user_screen = new UserScreen((GameScreen) s_instance.m_screen);
		s_instance.m_game_message = new GameMessage();
		s_instance.m_loading_screen = new LoadingScreen();
		// GameScene.initStaticResource();
		s_instance.img_lock_network = Tools.createImage(URL_IMG_LOCK_NETWORK);

		//#if edition == "JIUYOU" || edition == "JIUYOU_1" || edition == "JIUYOU_2" || edition == "JIUYOU_3" || edition == "JIUYOU_4"|| edition == "JIUYOU_5" || edition == "JIUYOU_6"
		//# s_instance.m_uc_sdk = UCGameSdk.defaultSdk();

		//# s_instance.m_uc_sdk.cpId = 688;
		//# s_instance.m_uc_sdk.gameId = 64364;
		//# s_instance.m_uc_sdk.serverId = 1002;

		//#if edition == "JIUYOU_1"
		//# s_instance.m_uc_sdk.channelId = 21;
		//#elif edition == "JIUYOU_2"
		//# s_instance.m_uc_sdk.channelId = 22;
		//#elif edition == "JIUYOU_3"
		//# s_instance.m_uc_sdk.channelId = 23;
		//#elif edition == "JIUYOU_4"
		//# s_instance.m_uc_sdk.channelId = 24;
		//#elif edition == "JIUYOU_5"
		//# s_instance.m_uc_sdk.channelId = 25;
		//#elif edition == "JIUYOU_6"
		//# s_instance.m_uc_sdk.channelId = 26;
		//#else
		//# s_instance.m_uc_sdk.channelId = 2;
		//#endif

		//# s_instance.m_uc_sdk.isDebug = false;
		//# Tools.debugPrintln("cpId="+s_instance.m_uc_sdk.cpId);
		//# Tools.debugPrintln("gameId="+s_instance.m_uc_sdk.gameId);
		//# Tools.debugPrintln("serverId="+s_instance.m_uc_sdk.serverId);
		//# Tools.debugPrintln("channelId="+s_instance.m_uc_sdk.channelId);
		//# Tools.debugPrintln("DEBUG="+s_instance.m_uc_sdk.isDebug);
		//# s_instance.m_uc_sdk.logLevel = UCLogLevel.OFF;

		//# s_instance.m_uc_sdk.gameMidlet = GameMIDlet.s_instance;
		//# s_instance.m_uc_sdk.gameCanvas = GameMIDlet.s_canvas;
		//# s_instance.m_uc_sdk.initSDK(new UCSdkListener() {
		//# public void onApiFinished(UCSdkEvent evt) {
		//# if (!evt.success) {
		//# s_instance.m_uc_msg = evt.msg;
		//# return;
		//# }
		//# s_instance.m_uc_msg = "SDK初始化成功!";
		//# s_instance.m_uc_inited = true;
		//# Tools.debugPrintln(s_instance.m_uc_msg);
		//# }
		//# });
		//#endif

//		s_instance.m_uc_sdk = UCGameSdk.defaultSdk();
//		s_instance.m_uc_sdk.cpId = 688;
//		s_instance.m_uc_sdk.gameId = 64364;
//		s_instance.m_uc_sdk.serverId = 1002;
//		s_instance.m_uc_sdk.channelId = 2;
//		s_instance.m_uc_sdk.isDebug = false;
//		s_instance.m_uc_sdk.logLevel = UCLogLevel.OFF;
//		s_instance.m_uc_sdk.gameMidlet = GameMIDlet.s_instance;
//		s_instance.m_uc_sdk.gameCanvas = GameMIDlet.s_canvas;
//		s_instance.m_uc_sdk.initSDK(new UCSdkListener() {
//		public void onApiFinished(UCSdkEvent evt) {
//		if (!evt.success) {
//			s_instance.m_uc_msg = evt.msg;
//			return;
//		}
//		s_instance.m_uc_msg = "SDK初始化成功!";
//		s_instance.m_uc_inited = true;
//		Tools.debugPrintln(s_instance.m_uc_msg);
//		}
//		});

		return s_instance;
	}

	public static GameManager getInstance()
	{
		return s_instance;
	}

	public AbstractGameScreen getScreen()
	{
		return m_screen;
	}

	/**
	 * 初始化玩家的时装头
	 *
	 * @param 性别
	 * @param 种族
	 * */
	public String getClothHead(int _sex, int _race)
	{
		_sex -= 1;
		_race -= 1;
		StringBuffer buff = new StringBuffer();
		String head = _sex == 0 ? "m_" : "f_";
		buff.append(head);
		switch (_race) {
			case 0:// 仙
				head = "x_";
				break;
			case 1:// 妖
				head = "y_";
				break;
			case 2:// 人
				head = "r_";
				break;
			case 3:// 鬼
				head = "g_";
				break;
		}
		buff.append(head);
		String temp = buff.toString();
		buff = null;
		return temp;
	}

	public static final int GS_TEST = -1;
	public static final int GS_COVER = 0; // 封面
	public static final int GS_USER = 1;// 用户中心
	public static final int GS_GAME = 2; // 游戏
	public static final int GS_LOADING = 4;
	public static final int GS_UI2 = 6;
	public static final int GS_RESEL = 5;//
	public static final int GS_D_TEST = 100;

	public int m_gameStatus = GS_USER;
//	public int m_gameStatus = GS_UI2;
	public static long s_ticks;

	public void setGameStatus(int gameStatus)
	{
		m_gameStatus = gameStatus;
		m_test_running = false;
		s_ticks = 0;
	}

	public void setReSelStatus(int gameStatus)
	{
		GameManager.getInstance().m_scene.m_isRunning = false;
		setGameStatus(gameStatus);
	}

	/** 系统设置 ----索引 */
//	public static final byte SET_SYSTEM_RANKS = 0;// 队伍开关
//	public static final byte SET_SYSTEM_RESEARCH = 1;// 切磋开关
//	public static final byte SET_SYSTEM_TRANSACTION = 2;// 交易开关
	public static final byte SET_SYSTEM_SOUND = 0;// 声音开关

	public static final byte SET_CHANNEL_WORLD = 1;// 世界频道
	public static final byte SET_CHANNEL_CAMP = 2;// 阵营频道
	public static final byte SET_CHANNEL_FMAILY = 3;// 家族频道
	public static final byte SET_CHANNEL_RANKS = 4;// 队伍频道
	public static final byte SET_CHANNEL_PRIVATE = 5;// 私聊频道
	public static final byte SET_CHANNEL_SYSTEM = 6;// 系统频道

	public static final byte SET_DIS_PLAYERS = 7;// 显示玩家
	// public static final byte SET_DIS_FRAME = 10;//画面效果
	public static final byte SET_DIS_WEATHER = 8;// 天气效果

	/** 系统设置信息 */
	public static byte[] s_system_infos;

	public String m_system_url = "set_system";

	/** 初始化 */
	public void initSystemInfos()
	{
		if (s_system_infos == null) {
			s_system_infos = new byte[9];
//			s_system_infos[SET_SYSTEM_RANKS] = 1;// 0关 1开
//			s_system_infos[SET_SYSTEM_RESEARCH] = 1;// 0关 1开
//			s_system_infos[SET_SYSTEM_TRANSACTION] = 1;// 0关 1开
			s_system_infos[SET_SYSTEM_SOUND] = 1;// 0关 1开
			s_system_infos[SET_CHANNEL_WORLD] = 1;// 0关 1开
			s_system_infos[SET_CHANNEL_CAMP] = 1;// 0关 1开
			s_system_infos[SET_CHANNEL_FMAILY] = 1;// 0关 1开
			s_system_infos[SET_CHANNEL_RANKS] = 1;// 0关 1开
			s_system_infos[SET_CHANNEL_PRIVATE] = 1;// 0关 1开
			s_system_infos[SET_CHANNEL_SYSTEM] = 1;// 0关 1开
			s_system_infos[SET_DIS_PLAYERS] = 2;// 0(优先自己和目标) 1(自己目标队友)2（全部）
			// s_system_infos[SET_DIS_FRAME] = 1;//0普通 1高等 2优秀
			s_system_infos[SET_DIS_WEATHER] = 1;// 0关 1开
		}

		if (Tools.haveRecord(m_system_url)) {// 判断有存档取数据赋值
			byte[] mirr = Tools.loadRecord(m_system_url, 1);
			if (mirr == null) {
				Tools.saveRecord(s_system_infos, m_system_url, 1);
				Tools.debugPrintln("系统设置读出存档数据出错！");
			}
			else {
				int length = mirr.length;
				if (s_system_infos.length == length) {
					s_system_infos = mirr;
				}
				else {
					Tools.saveRecord(s_system_infos, m_system_url, 1);
					Tools.debugPrintln("系统设置读出存档数据出错！");
				}
			}
		}
		Tools.saveRecord(s_system_infos, m_system_url, 1);
	}

	/**
	 * 更改系统设置
	 *
	 * @param byte[] 系统设置的数据
	 **/
	public void changeSetSystem(byte[] data)
	{
		int length = data.length;
		if (length == s_system_infos.length) {
			for (byte i = 0; i < length; i++) {
				if (s_system_infos[i] != data[i]) {// 如果设置数据有更改，详细操作
					s_system_infos[i] = data[i];
					changeSetSystem(i, true, false);
				}
			}
		}
	}

	/**
	 * 判断系统设置是否有变化
	 *
	 * @param boolean true 改变 false 没改变
	 * */
	public boolean isChangeSetSystem(byte[] data)
	{
		int length = data.length;
		if (length == s_system_infos.length) {
			for (byte i = 0; i < length; i++) {
				if (s_system_infos[i] != data[i]) {// 如果设置数据有更改，详细操作
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 按类型改变处理系统设置
	 *
	 * @param type
	 * 系统设置类型
	 * @param boolean 是否需要存盘
	 * @param boolean 是否全部设置
	 */
	public void changeSetSystem(byte type, boolean save, boolean all)
	{
		boolean flag = false;
		do {
			Tools.debugPrintln("GameManger setSystem:type=" + type);
			switch (type) {
//			case SET_SYSTEM_RANKS:// 队伍开关
//			case SET_SYSTEM_RESEARCH:// 切磋开关
//			case SET_SYSTEM_TRANSACTION:// 交易开关
//				break;
				case SET_CHANNEL_WORLD:// 世界频道
					// if (s_system_infos[type] == 0) {
					// GameManager.getInstance().m_game_message.sendChatOpen(ChatItem.TYPE_WORLD);
					// }else{
					// GameManager.getInstance().m_game_message.sendChatPingBi(ChatItem.TYPE_WORLD);
					// }
					break;
				case SET_CHANNEL_CAMP:// 阵营频道
//					if (s_system_infos[type] == 0) {
//						GameManager.getInstance().m_game_message.sendChatOpen(ChatItem.TYPE_REALM);
//					}
//					else {
//						GameManager.getInstance().m_game_message.sendChatPingBi(ChatItem.TYPE_REALM);
//					}
				case SET_CHANNEL_FMAILY:// 家族频道
					// if (s_system_infos[type] == 0) {
					// GameManager.getInstance().m_game_message.sendChatOpen(ChatItem.TYPE_FAMILY);
					// }else{
					// GameManager.getInstance().m_game_message.sendChatPingBi(ChatItem.TYPE_FAMILY);
					// }
					break;
				case SET_CHANNEL_RANKS:// 队伍频道
					// if (s_system_infos[type] == 0) {
					// GameManager.getInstance().m_game_message.sendChatOpen(ChatItem.TYPE_TEAM);
					// }else{
					// GameManager.getInstance().m_game_message.sendChatPingBi(ChatItem.TYPE_TEAM);
					// }
					break;
				case SET_CHANNEL_PRIVATE:// 私聊频道
					// if (s_system_infos[type] == 0) {
					// GameManager.getInstance().m_game_message.sendChatOpen(ChatItem.TYPE_SI);
					// }else{
					// GameManager.getInstance().m_game_message.sendChatPingBi(ChatItem.TYPE_SI);
					// }
					break;
				case SET_DIS_PLAYERS:// 显示玩家
					// case SET_DIS_FRAME://画面效果
				case SET_DIS_WEATHER:// 天气效果
				default:
					break;
				case SET_SYSTEM_SOUND:// 声音开关
					flag = s_system_infos[SET_SYSTEM_SOUND] == 0 ? false : true;
					if (flag) {
						Music.getInstance().openMusic();
						Music.getInstance().loadBackground(Music.SOUND_BG_FILE_NAME,
								Music.getInstance().getCurBackGroundId());
						Music.getInstance().playBackground();
					}
					else {
						Music.getInstance().closeMusic();
					}
					break;
			}
			if (all) {// 所有都处理后存盘
				type++;
				if (type >= s_system_infos.length) {
					all = false;
					if (save) {
						Tools.saveRecord(s_system_infos, m_system_url, 1);
					}
				}
			}
			else {
				if (save) {
					Tools.saveRecord(s_system_infos, m_system_url, 1);
				}
			}
		}
		while (all);
	}

	public static final int FRAME_INTERVAL = 100;
	public static final int FRAME_PER_SECOND = 1000 / FRAME_INTERVAL;

	// 用于显示帧数
	// public static boolean SHOWTIME = false;
	// private static long s_fps_start = 0;
	// private static long s_fps_end = 0;
	// public static int s_fps = 0;
	// public static long s_flushTime = 0;
	// public static int s_repaintTime = 0;
	// public static long s_tickCount = 0;

	public static long s_worldTimeServer = 0;
	public static long s_worldTimeDelay = 0;
	// public static long s_worldTime

	public static boolean s_isRunning = true;
	public static boolean s_pauseRun = false;

	/**
	 * 游戏线程处理函数 作用：主要用来控制游戏的速度
	 */
	public void run()
	{
		long tick;

		while (s_isRunning) {
			if (s_pauseRun) {
				Thread.yield();
				continue;
			}
			tick = System.currentTimeMillis() + FRAME_INTERVAL;
			Tools.debugPrintln("m_gameStatus : " + m_gameStatus);
			try {
				switch (m_gameStatus) {
					case GS_COVER:
						break;
					case GS_USER:
						runUser();
						break;
					case GS_GAME:
						runGame();
						break;
					case GS_TEST:
						runTest();
						break;
					case GS_LOADING:
						runLoading();
						break;
					case GS_RESEL:
						runReselect();
						break;
					case GS_UI2:
						runUi2();
						break;
					case GS_D_TEST:
						runDTest();
						break;
				}
			}
			catch (Exception ex) {
				Tools.debug(ex);
				Tools.debugPrintln("run exception : " + ex.toString());
				Tools.debugPrintln("run message : " + ex.getMessage());
				// dealForConnectionException();
			}
			while (System.currentTimeMillis() < tick) {
				Thread.yield();
			}
		}
		s_instance = null;
		GameMIDlet.s_instance.destroyApp(true);
		GameMIDlet.s_instance = null;
	}

	public UIShowData m_showData = null;
	public UITaskWindow m_task_window = null;
	public UINPCWindow m_npc_window = null;
	public UILifeSkillsWindow m_life_skills_window = null;
	public UIFamilyWindow m_family_window = null;

	private void runDTest()
	{
		Graphics g = m_screen.getGraphics();
		m_test_running = true;
		long tick;

		int count = 20;
		int angle = 0;
		int w = 20;
		int h = 32;
		int select = 0;
		int speed = 0;
		int timer = 0;
		int ran = 0;
		boolean control = true;// 是否接受控制
		boolean start = false;

		while (m_test_running) {
			tick = System.currentTimeMillis() + GameManager.FRAME_INTERVAL;
			AbstractGameScreen.updateKeyBegin();

			g.setColor(Tools.WHITE);
			g.fillRect(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);

			// draw
			String text = "";
			for (int i = 0, x = 0, y = 0; i < count; i++) {
				x = (AbstractGameScreen.SCREEN_WIDTH >> 1) + 3
						+ (Tools.sin(i * (360 / count) + angle << Tools.BITS) * 100 >> Tools.BITS);
				y = (AbstractGameScreen.SCREEN_HEIGHT >> 1)
						- (Tools.cos(i * (360 / count) + angle << Tools.BITS) * 120 >> Tools.BITS);
				text = "" + i;
				g.setColor(Tools.BLACK);
				g.fillRect(x - (w >> 1), y - (h >> 1), w, h);
				g.setColor(Tools.WHITE);
				g.drawString(text, x - (AbstractGameScreen.s_font.stringWidth(text) >> 1), y
						- (AbstractGameScreen.FONT_H >> 1), Tools.LEFT_TOP);

				if (i == select) {
					g.setColor(Tools.YELLOW);
					g.drawRect(x - (w >> 2), y - (h >> 2), w >> 1, h >> 1);
				}
				g.setColor(Tools.BLACK);
				if (start) {
					g.drawString("停止", AbstractGameScreen.SCREEN_WIDTH >> 1, (AbstractGameScreen.SCREEN_HEIGHT >> 1)
							- (AbstractGameScreen.FONT_H >> 1), Tools.HCENTER_TOP);
				}
				else {
					g.drawString("开始", AbstractGameScreen.SCREEN_WIDTH >> 1, (AbstractGameScreen.SCREEN_HEIGHT >> 1)
							- (AbstractGameScreen.FONT_H >> 1), Tools.HCENTER_TOP);
				}
			}
			// logic
			if (start) {
				if (control) {
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						control = false;
					}
				}
				else {
					if (timer % 10 == 0 && speed < 7) {
						speed++;
					}
				}
				if (timer % (speed + 1) == 0) {
					if (++select >= count) {
						select = 0;
					}
				}
				if (speed >= 4 && select == ran) {
					start = false;
					control = true;
				}
			}
			else {
				if (control) {
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						start = true;
						speed = 0;
						ran = Tools.getRandom(0, count - 1);
						Tools.debugPrintln("本次结果 : " + ran);
					}
				}
			}

			keepConnectionAlive();
			m_screen.flush();
			AbstractGameScreen.updateKeyEnd();
			while (tick > System.currentTimeMillis()) {
				Thread.yield();
			}
			if (++timer > 100000) {
				timer = 0;
			}
		}
	}

	private void runReselect()
	{
		// m_resource_scene.removeAll();
		if (m_user_screen == null) {
			m_user_screen = new UserScreen();
		}
		m_loading_screen.m_progress = 0;
		m_user_screen.m_user_state = UserScreen.STATE_LOGIN_BACK;
		m_user_screen.m_reselect_time = 0;
		setGameStatus(GameManager.GS_USER);
		UIMain.s_spell_srcx = 0;
		UIMain.s_spell_type = 1;
		UIMain.s_spell_x = AbstractGameScreen.SCREEN_WIDTH;
	}

	private void runUi2()
	{
		UIManager.createInstance();
		UIManager.createColors();
		UIManager.createImages();
		UITools.initImage();
		//
		GameScene.initStaticResource();
		Graphics g = m_screen.getGraphics();
		m_test_running = true;
		long tick;
		// 初始化各项
		m_role = new ActorRole();
		m_role.m_bag_equipment = new ActorItem[ActorRole.NUM_BAG_EQUIPMENT];
		for (int i = 0; i < ActorRole.NUM_BAG_EQUIPMENT; i++) {
			m_role.m_bag_equipment[i] = ActorItem.getTestItem(ActorItem.TYPE_BAG_EQUIP, i);
		}
		m_role.m_bag_goods = new ActorItem[ActorRole.NUM_BAG_GOODS];
		for (int i = 0; i < 10; i++) {
			m_role.m_bag_goods[i] = ActorItem.getTestItem(ActorItem.TYPE_BAG_ROLE, i);
		}
		m_role.m_money_game = 100;
//	private void runUi2()
//	{
//		UIManager.createInstance();
//		UIManager.createColors();
//		UIManager.createImages();
//		UITools.initImage();
//		//
//		GameScene.initStaticResource();
//		Graphics g = m_screen.getGraphics();
//		m_test_running = true;
//		long tick;
//		// 初始化各项
//		m_role = new ActorRole();
//		m_role.m_bag_equipment = new ActorItem[ActorRole.NUM_BAG_EQUIPMENT];
//		for (int i = 0; i < ActorRole.NUM_BAG_EQUIPMENT; i++) {
//			m_role.m_bag_equipment[i] = ActorItem.getTestItem(ActorItem.TYPE_BAG_EQUIP, i);
//		}
//		m_role.m_bag_goods = new ActorItem[ActorRole.NUM_BAG_GOODS];
//		for (int i = 0; i <18; i++) {
//			m_role.m_bag_goods[i] = ActorItem.getTestItem(ActorItem.TYPE_BAG_ROLE, i);
//		}
//		m_role.m_money_game = 100;
//
//		// GameManager.getInstance().m_game_macro = new GameMacro[4];
//		// for (int i = 0; i < GameManager.getInstance().m_game_macro.length;
//		// i++) {
//		// GameManager.getInstance().m_game_macro[i] = new GameMacro();
//		// GameManager.getInstance().m_game_macro[i].initActions();
//		// }
//
//		Random random = new Random();
//		RoleCombatSkill[][] skill = new RoleCombatSkill[2][3];
//		for (int i = 0; i < skill.length; i++) {
//			for (int j = 0; j < skill[i].length; j++) {
//				skill[i][j] = new RoleCombatSkill();
//				skill[i][j].m_id = (short) Tools.getRandom(0, 80);
//				skill[i][j].m_iconCoverId = (short) Tools.getRandom(0, 80);
//			}
//		}
//		GameManager.getInstance().m_role.m_roleCombatSkill = skill;
//		GameManager.getInstance().m_role.m_anim = new Animation();
//		GameManager.getInstance().m_role.m_anim.m_resHead = new ResHead();
//		GameManager.getInstance().m_role.m_anim.m_resHead.m_url = "";
//		// ResHead resHead = new ResHead(ObjectAdapter.RESOURCE_TYPE_ANIM,
//		// GameManager.getInstance().m_role.m_anim.m_resHead.m_url, 1);
//		// GameManager.getInstance().m_role.m_anim = (Animation)
//		// (ResourceManager.getInstance().loadResource(GameManager
//		// .getInstance().m_resource_scene, resHead));
//		//
//		long[][][] shortcut = new long[2][8][2];
//		for (int i = 0; i < shortcut.length; i++) {
//			for (int j = 0; j < shortcut[i].length; j++) {
//				shortcut[i][j][0] = AbstractGameActor.ACTION_TYPE_NONE;
//				shortcut[i][j][1] = AbstractGameActor.ACTION_TYPE_NONE;
//			}
//		}
//		GameManager.getInstance().m_role.m_shortcut = shortcut;
//
//		GameManager.getInstance().m_role.m_roleCombatSkill = new RoleCombatSkill[2][];
//		for (int i = 0; i < 1; i++) {
//			GameManager.getInstance().m_role.m_roleCombatSkill[i] = new RoleCombatSkill[49];
//			for (int j = 0; j < GameManager.getInstance().m_role.m_roleCombatSkill[i].length; j++) {
//				GameManager.getInstance().m_role.m_roleCombatSkill[i][j] = RoleCombatSkill.getTestRoleSkill(random);
//			}
//		}
//
//		GameManager.getInstance().m_role.m_name = "name_player";
//
//		ActorItemEquip equip = new ActorItemEquip();
//		int size = 8;
//		equip.m_color_jewels = new byte[size];
//		equip.m_isXiangqian_jewels = new boolean[size];
//		for (int i = 0; i < size; i++) {
//			equip.m_color_jewels[i] = ActorItemEquip.COLOR_JEWEL_BLUE;
//			equip.m_isXiangqian_jewels[i] = true;
//		}
//		equip.m_name = "testEquip";
//		equip.m_level_defence = 2;
//		equip.m_level_magic = 3;
//		equip.m_level_phy = 40;
//		equip.m_type = ActorItem.TYPE_BAG_EQUIP;
//		equip.m_type_detail = ActorItem.TYPE_EQUIPMENT_WEAPON_SIN;
//		GameManager.getInstance().m_role.m_bag_goods[0] = equip;
//
//		GameScene.initStaticResource();
//		// testUIRankingLists();
//		// UIChongzhi.testRecord();
//		// testFBactivity();
//		// testCollection();
//		// testAnnouncement();
//		// testActivity();
//		// testSocial();
//		// UISetShortCut.gotoSetShortcut();
//		// UIChatInsert.gotoInsetGood() ;
//		// UIGameManager.getInstance().m_game_message.unlockNetwork();ChatInsert.gotoInsetPic();
//		// UIChatFace.gotoChatGongliao(null) ;
//		// UIMenu.openMenu(true);
////		 UIMenu.openMenu(false);
//		// testDONGFU();
//		// UIChatInsert.gotoSiliao("Hello");
//		// UIChongzhi.testRecord();
//
//		// UITaskWindow.gotoTeach();
//		// UIMenu.gotoTeachTask();
//		// UISetShortCut.gotoTeachSetShortcut();
//
//		// UICaveWorldWindow.testDonfu() ;
//		// UIManager.getInstance().addWindow(UIWindowFactory.createWindow(UIWindowFactory.WINDOW_SET_SHORTCUT));
//
//		UIMain.ID_SET_SKILL = m_role.m_roleCombatSkill[0][2].m_id;
//		// UIMenu.gotoTeachSetShortcut() ;
//		// UIMailList2.test();
//		// UIAttribute.test() ;
//		// UIMenu.openMenuInEquip();
//		// UIMarket.gotoBuy("Test", 8739821, 0, 100) ;
//
////		UIGonglue.test() ;
////		UIQianghua.test();
//		UIAuctionSearch.test();
//
//		while (m_test_running) {
//			tick = System.currentTimeMillis() + GameManager.FRAME_INTERVAL;
//			AbstractGameScreen.updateKeyBegin();
//			// 清屏
//			UIManager.getInstance().paint(g);
//			UIManager.getInstance().logic();
//
//			if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)) {
//				GameManager.getInstance().addSysMessage("dsdsadsadasdsa");
//			}
//			m_screen.flush();
//			AbstractGameScreen.updateKeyEnd();
//			while (tick > System.currentTimeMillis()) {
//				Thread.yield();
//			}
//		}
//	}
		// GameManager.getInstance().m_game_macro = new GameMacro[4];
		// for (int i = 0; i < GameManager.getInstance().m_game_macro.length;
		// i++) {
		// GameManager.getInstance().m_game_macro[i] = new GameMacro();
		// GameManager.getInstance().m_game_macro[i].initActions();
		// }

		Random random = new Random();
		RoleCombatSkill[][] skill = new RoleCombatSkill[2][3];
		for (int i = 0; i < skill.length; i++) {
			for (int j = 0; j < skill[i].length; j++) {
				skill[i][j] = new RoleCombatSkill();
				skill[i][j].m_id = (short) Tools.getRandom(0, 80);
				skill[i][j].m_iconCoverId = (short) Tools.getRandom(0, 80);
			}
		}
		GameManager.getInstance().m_role.m_roleCombatSkill = skill;
		GameManager.getInstance().m_role.m_anim = new Animation();
		GameManager.getInstance().m_role.m_anim.m_resHead = new ResHead();
		GameManager.getInstance().m_role.m_anim.m_resHead.m_url = "";
		// ResHead resHead = new ResHead(ObjectAdapter.RESOURCE_TYPE_ANIM,
		// GameManager.getInstance().m_role.m_anim.m_resHead.m_url, 1);
		// GameManager.getInstance().m_role.m_anim = (Animation)
		// (ResourceManager.getInstance().loadResource(GameManager
		// .getInstance().m_resource_scene, resHead));
		//
		long[][][] shortcut = new long[2][8][2];
		for (int i = 0; i < shortcut.length; i++) {
			for (int j = 0; j < shortcut[i].length; j++) {
				shortcut[i][j][0] = AbstractGameActor.ACTION_TYPE_NONE;
				shortcut[i][j][1] = AbstractGameActor.ACTION_TYPE_NONE;
			}
		}
		GameManager.getInstance().m_role.m_shortcut = shortcut;

		GameManager.getInstance().m_role.m_roleCombatSkill = new RoleCombatSkill[2][];
		for (int i = 0; i < 1; i++) {
			GameManager.getInstance().m_role.m_roleCombatSkill[i] = new RoleCombatSkill[49];
			for (int j = 0; j < GameManager.getInstance().m_role.m_roleCombatSkill[i].length; j++) {
				GameManager.getInstance().m_role.m_roleCombatSkill[i][j] = RoleCombatSkill.getTestRoleSkill(random);
			}
		}

		GameManager.getInstance().m_role.m_name = "name_player";

		ActorItemEquip equip = new ActorItemEquip();
		int size = 8;
		equip.m_color_jewels = new byte[size];
		equip.m_isXiangqian_jewels = new boolean[size];
		for (int i = 0; i < size; i++) {
			equip.m_color_jewels[i] = ActorItemEquip.COLOR_JEWEL_BLUE;
			equip.m_isXiangqian_jewels[i] = true;
		}
		equip.m_name = "testEquip";
		equip.m_level_defence = 2;
		equip.m_level_magic = 3;
		equip.m_level_phy = 40;
		equip.m_type = ActorItem.TYPE_BAG_EQUIP;
		equip.m_type_detail = ActorItem.TYPE_EQUIPMENT_WEAPON_SIN;
		GameManager.getInstance().m_role.m_bag_goods[0] = equip;

		GameScene.initStaticResource();
		// testUIRankingLists();
		// UIChongzhi.testRecord();
		// testFBactivity();
		// testCollection();
		// testAnnouncement();
		// testActivity();
		// testSocial();
		// UISetShortCut.gotoSetShortcut();
		// UIChatInsert.gotoInsetGood() ;
		// UIGameManager.getInstance().m_game_message.unlockNetwork();ChatInsert.gotoInsetPic();
		// UIChatFace.gotoChatGongliao(null) ;
		// UIMenu.openMenu(true);
//		 UIMenu.openMenu(false);
		// testDONGFU();
		// UIChatInsert.gotoSiliao("Hello");
		// UIChongzhi.testRecord();

		// UITaskWindow.gotoTeach();
		// UIMenu.gotoTeachTask();
		// UISetShortCut.gotoTeachSetShortcut();

		// UICaveWorldWindow.testDonfu() ;
		// UIManager.getInstance().addWindow(UIWindowFactory.createWindow(UIWindowFactory.WINDOW_SET_SHORTCUT));

		UIMain.ID_SET_SKILL = m_role.m_roleCombatSkill[0][2].m_id;
		// UIMenu.gotoTeachSetShortcut() ;
		// UIMailList2.test();
		// UIAttribute.test() ;
		// UIMenu.openMenuInEquip();
		// UIMarket.gotoBuy("Test", 8739821, 0, 100) ;

		while (m_test_running) {
			tick = System.currentTimeMillis() + GameManager.FRAME_INTERVAL;
			AbstractGameScreen.updateKeyBegin();
			// 清屏
			UIManager.getInstance().paint(g);
			UIManager.getInstance().logic();

			if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)) {
				GameManager.getInstance().addSysMessage("dsdsadsadasdsa");
			}
			m_screen.flush();
			AbstractGameScreen.updateKeyEnd();
			while (tick > System.currentTimeMillis()) {
				Thread.yield();
			}
		}
	}

	// private void testInterMenu()
	// {
	// UiInteractMenu interactMenu = UiInteractMenu
	// .openInteractMenu(
	// "key",
	// "<dialog>对话内容1</dialog><dialog win=1>对话内容2</dialog><dialog name=</dialo>对话内容3</dialog><dialog win=2 name=nameX>对话内容4</dialog>");
	// interactMenu.addListener(new UIListener() {
	//
	// public void actionPerformed()
	// {
	// System.err.println("InterMenu Over");
	// }
	// });
	//
	// String temp = null;
	// for (int i = 0; i < 20; i++) {
	// for (int j = 0; j < 20; j++) {
	// temp = null;
	// temp = "" + i + " " + j;
	// }
	// }
	// }
	//
	// private void testDONGFU()
	// {
	// UICaveWorldWindow df = (UICaveWorldWindow)
	// UIManager.getInstance().createWindow(
	// UIWindowFactory.WINDOW_ID_DONGFU);
	// }

	//
	// private void testPopmenu()
	// {
	// final UIPopmenu popmenu = (UIPopmenu) UIManager.getInstance()
	// .createWindow(UIWindowFactory.WINDOW_POPMENU);
	// final String[] menus = new String[5];
	// menus[0] = new String("测试换色等操作 " + 0);
	// menus[1] = new String("测试换色等 " + 1);
	// menus[2] = new String("测试换 " + 2);
	// menus[3] = new String("测 " + 3);
	// menus[4] = new String(" " + 4);
	//
	// popmenu.setPopmenus(menus);
	// popmenu.addListener(new UIListener() {
	//
	// public void actionPerformed()
	// {
	// if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)
	// || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)) {
	// System.out.println(popmenu.getCurrentIndex());
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY1)) {
	// popmenu.setPopmenus(menus, popmenu.ALIGN_CENTRE);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY2)) {
	// popmenu.setPopmenus(menus, popmenu.ALIGN_RIGHT);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY3)) {
	// popmenu.setPopmenus(null);
	// }
	// }
	// });
	// }
	//
	// private void testSocial()
	// {
	// Vector list = GameManager.getInstance().m_social_list;
	// for (int i = 0; i < 2; i++) {
	// SimpleRole role = new SimpleRole();
	// role.m_gameID = 1000;
	// role.m_name = "小小";
	// list.addElement(role);
	// }
	// UISocialWindow social = (UISocialWindow)
	// UIManager.getInstance().createWindow(
	// UIWindowFactory.WINDOW_ID_SOCIAL_ENEMY);
	// social.m_unitRollx=new int[3];
	// for (int i = 0; i < 2; i++) {
	// social.m_unitRollx[i]=0;
	// }
	// social.m_enemyStatus = 1;
	// social.memberIndex = 0;
	// }
	//
	// private void testTeam()
	// {
	// // UITeamWindow team = (UITeamWindow)
	// UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_ID_TEAMNEAR);
	// }
	//
	// private void testMail()
	// {
	// UIMail mail = (UIMail)
	// UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MAIL);
	// }
	//
	// private void testAlertBox()
	// {
	// String testMark = null;
	// // 测试AlertBox
	// testMark = "大红的户籍卡刷卡机的和萨科技韩德君阿什顿";
	// testMark =
	// "Nor~m`a`l`<mark t=1,i=11123,c=879878,b=1,u=1><replace t=6,i=2></replace></mark>NTestOR~MAL<replace t=4,i=2></replace>NORMAL<mark t=1,i=11123,c=ffff00,b=1,u=1>NORMAL</mark>NORMAL";
	// UIMessageBox messageBox2 = (UIMessageBox)
	// UIManager.getInstance().createWindow(
	// UIWindowFactory.WINDOW_MESSAGEBOX);
	// messageBox2.setMessage(null, null, null, testMark);
	// }
	//
	// private void testMessageBox()
	// {
	// String testMark = null;
	// testMark =
	// "Nor~m`a`l`<mark t=1,i=11123,c=879878,b=1,u=1><replace t=6,i=2></replace></mark>NTestOR~MAL<replace t=4,i=2></replace>NORMAL<mark t=1,i=11123,c=ffff00,b=1,u=1>NORMAL</mark>NORMAL";
	// testMark = "大红的户籍卡刷卡机的和萨科技韩德君阿什顿";
	// final UIMessageBox messageBox = (UIMessageBox)
	// UIManager.getInstance().createWindow(
	// UIWindowFactory.WINDOW_MESSAGEBOX);
	// messageBox.setMessage("Titke", null, null, testMark);
	// // messageBox.setMessage(testMark);
	// messageBox.addListener(new UIListener() {
	//
	// public void actionPerformed()
	// {
	// if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.RIGHT_SOFT)) {
	// UIManager.getInstance().removeWindow(messageBox);
	// }
	// }
	// });
	// }

//	private void testUIRankingLists() {
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		DataOutputStream dos = new DataOutputStream(baos);
//		;
//		try {
//			dos.writeByte(2);
//		} catch (IOException e) {
//		}
//		ByteArrayInputStream das = new ByteArrayInputStream(baos.toByteArray());
//		DataInputStream dis = new DataInputStream(das);
//		try {
//			UIRankingLists.recvLevelRankingList(dis);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	// public byte[] t_type = {1,1,2,2,1,1,2};
	// public byte[] t_data1 = {1,1,1,1,1,0,1};
	// public byte[] t_data2 = {0,0,10,8,0,0,10};
	// public byte[] t_lv = {30,20,10,20,30,20,10};
	// public String[] t_name =
	// {"三方战场","龙华会武","比武招亲","一溜烟","三方战场","龙华会武","比武招亲"};
	// public String[] t_time =
	// {"13:00-14:00","08:00-10:00","全天均可","全天50次","13:00-14:00","08:00-10:00","全天均可"};
	// public String[] t_descip =
	// {"可获得战功","可获得美人","可获得金钱","可获得儿子","可获得战功","可获得美人","可获得金钱"};

	// public byte[] t_type = {1,1};
	// public byte[] t_data1 = {1,1};
	// public byte[] t_data2 = {0,0};
	// public byte[] t_lv = {30,20};
	// public String[] t_name = {"三方战场","龙华会武"};
	// public String[] t_time = {"13:00-14:00","08:00-10:00"};
	// public String[] t_descip = {"可获得战功","可获得美人"};

	// private void testFBactivity(){
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// DataOutputStream dos = new DataOutputStream(baos);;
	// try {
	// dos.writeByte(1);
	// int num = t_type.length;
	// dos.writeByte(num);
	// for(int i=0;i<num;i++){
	// dos.write(t_type[i]);
	// dos.write(t_data1[i]);
	// dos.write(t_data2[i]);
	// dos.write(t_lv[i]);
	// dos.writeUTF(t_name[i]);
	// dos.writeUTF(t_time[i]);
	// dos.writeUTF(t_descip[i]);
	// }
	// }
	// catch (IOException e) {
	// }
	// ByteArrayInputStream das = new ByteArrayInputStream(baos.toByteArray());
	// DataInputStream dis = new DataInputStream(das);
	// try {
	// UIFbactivity.recvUIFbactivity(dis);
	// }
	// catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	/*
	 * private void testCollection(){ ByteArrayOutputStream baos = new
	 * ByteArrayOutputStream(); DataOutputStream dos = new
	 * DataOutputStream(baos);; try { dos.writeByte(1); dos.writeByte(1); //
	 * dos.writeByte(1); // dos.writeByte(30); dos.writeByte(0);
	 * dos.writeLong(99999); dos.writeInt(10); dos.writeShort(1);
	 * dos.writeUTF("定海神针"); } catch (IOException e) { } ByteArrayInputStream
	 * das = new ByteArrayInputStream(baos.toByteArray()); DataInputStream dis =
	 * new DataInputStream(das); try {
	 * UILearnCollection.recvForgetCollection(dis); } catch (Exception e) {
	 * e.printStackTrace(); } }
	 */

//	 private void testAnnouncement(){
//	 ByteArrayOutputStream baos = new ByteArrayOutputStream();
//	 DataOutputStream dos = new DataOutputStream(baos);;
//	 try {
//      dos.writeUTF("本游戏周末将开启第一大服，请玩家注意抢购注册！本游戏周末将开启第一大服，请玩家注意抢购注册！本游戏周末将开启第一大服，请玩家注意抢购注册！本游戏周");
//      String[] str = {"系统公告","副本公告","活动公告","玩家公告","系统公告","副本公告","活动公告","玩家公告","系统公告","副本公告","活动公告","玩家公告"};
//      int size = str.length;
//      dos.write(size);
//      for(int i=0;i<size;i++){
//    	  dos.writeUTF(str[i]);
//      }
//	 }
//	 catch (IOException e) {
//	 }
//	 ByteArrayInputStream das = new ByteArrayInputStream(baos.toByteArray());
//	 DataInputStream dis = new DataInputStream(das);
//	 try {
//	    UIAnnouncement.recvAnnouncement(dis);
//	 }
//	 catch (Exception e) {
//	 e.printStackTrace();
//	 }
//	 }

	// private void testWanted()
	// {
	// long[] wID = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	// long[] mID = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	// String[] name = { "武飘飘夫人的裙子和内裤", "武夫人", "夫人武飘飘夫人的裙子和内裤", "Adaliya",
	// "武飘飘夫人", "武夫人", "夫人", "Adaliya", "武飘飘夫人", };
	// byte[] type = { 0, 1, 0, 1, 1, 0, 0, 1, 1 };
	// long[] money = { 9999, 99999, 999999, 44324, 12321, 123, 453, 765, 39 };
	// int[] time = { 55, 0, 345, 23, 11, 675, 32, 10, 66 };
	//
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// DataOutputStream dos = new DataOutputStream(baos);
	//
	// short length = (short) (wID.length);
	// try {
	// dos.writeByte(0);
	// dos.writeShort(10);
	// dos.writeByte(0);
	// dos.writeShort(9);
	// dos.writeShort(length);
	// for (int i = 0; i < length; i++) {
	// dos.writeLong(wID[i]);
	// dos.writeLong(mID[i]);
	// dos.writeUTF(name[i]);
	// dos.writeByte(type[i]);
	// dos.writeLong(money[i]);
	// dos.writeInt(time[i]);
	// }
	// }
	// catch (IOException e) {
	// }
	// ByteArrayInputStream das = new ByteArrayInputStream(baos.toByteArray());
	// DataInputStream dis = new DataInputStream(das);
	// try {
	// UIWanted.recvWantedInfos(dis);
	// }
	// catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// }

	// private void testMenu()
	// {
	//
	// final UIDialogMenu menu = (UIDialogMenu)
	// UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MENU);
	// // menu.setSupprotDrag(true);
	// // menu.setSupprotPage(true);
	// final String[] menus = new String[23];
	// Random random = new Random();
	// for (int i = 0; i < menus.length; i++) {
	// char[] chars = new char[random.nextInt(20) + 10];
	// for (int j = 0; j < chars.length; j++) {
	// chars[j] = (char) (random.nextInt(20) + 60);
	// }
	// menus[i] = String.valueOf(chars) + " i";
	// }
	// // String testMark =
	// //
	// "Nor~m`a`l`<mark t=1,i=11123,c=879878,b=1,u=1><replace t=6,i=2></replace></mark>NTestOR~MAL<replace t=4,i=2></replace>NORMAL<mark t=1,i=11123,c=ffff00,b=1,u=1>NORMAL</mark>NORMAL";
	// String testMark = "和健康和的控件哈孔得红";
	// menu.setContents("Npc", testMark, menus);
	// // menu.setContents("Hello", null, menus);
	// // menu.setContents(null, null, menus);
	// menu.addListener(new UIListener() {
	// public void actionPerformed() {
	// if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
	// || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
	// int index = menu.getCurrentIndex();
	// }
	// else if
	// (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
	// UIManager.getInstance().removeWindow(menu);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY1)) {
	// menu.setContents(null, null, null);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY2)) {
	// menu.setContents(null, null, menus);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY3)) {
	// menu.setContents(null, "test", null);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY4)) {
	// menu.setContents(null, "test", menus);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY5)) {
	// menu.setContents("Npc", null, null);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY6)) {
	// menu.setContents("Npc", null, menus);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY7)) {
	// menu.setContents("Npc", "test", null);
	// }
	// else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY8)) {
	// menu.setContents("Npc", "test", menus);
	// }
	// }
	// });
	// }

	private TextBox textBox = new TextBox(TextBox.STYLE_TEXTWIN, AbstractGameScreen.SCREEN_WIDTH,
			AbstractGameScreen.SCREEN_HEIGHT, Tools.BLACK, Tools.BLACK, Tools.WHITE,
			TextBox.ADJUST_NONE);

	private void setDebugLog()
	{
		int size = Tools.m_debug_log.size() - 1;
		String text = "";
		for (int i = size; i >= 0; i--) {
			text += (Tools.m_debug_log.elementAt(i).toString() + '\n');
		}
		textBox.setText(text);
	}

	public boolean debugLogLogic()
	{
		if (Tools.DEBUG) {
			if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_KEY7)) {
				Tools.m_open_log = !Tools.m_open_log;
				if (Tools.m_open_log) {
					setDebugLog();
					return true;
				}
			}
			if (Tools.m_open_log) {
				textBox.logic();
				return true;
			}
		}
		return false;
	}

	public boolean debugLogDraw(Graphics g)
	{
		if (Tools.DEBUG) {
			if (Tools.m_open_log) {
				textBox.render(g, 0, 0);
				return true;
			}
		}
		return false;
	}

	public void runUser()
	{
		Graphics g = m_screen.getGraphics();
		m_test_running = true;
		long tick;
		while (m_test_running) {
			tick = System.currentTimeMillis() + GameManager.FRAME_INTERVAL;
			if (!m_pause_run) {
				AbstractGameScreen.updateKeyBegin();
				GameManager.getInstance().debugLogLogic();
				if (m_game_message != null) {
					if (m_game_message.networkTimeLogic()) {
						Tools.debugPrintln("UserScreen network exception!");
						s_isControlledByUi = true;
						dealForConnectionException();
					}
				}
				m_user_screen.paint(g);
				m_user_screen.logic();
				if (m_game_message != null) {
					m_game_message.drawNetworkTime(g);
				}
				GameManager.getInstance().debugLogDraw(g);

				keepConnectionAlive();
				m_screen.flush();
				AbstractGameScreen.updateKeyEnd();
			}
			while (tick > System.currentTimeMillis()) {
				Thread.yield();
			}
		}
	}

	public void runGame()
	{
		// m_scene = m_curScene;
		m_scene.run();
	}

	// private byte[] m_counter = {25, 60, 85, 100};//0-20释放, 30-60加载,
	// 60-85请求资源, 85-100预留
	// private byte m_counter_index = 0;
	public int m_counter = 0;// loading计时器
	private static int m_loading_timer = 0;//

	public void runLoading()
	{
		Graphics g = m_screen.getGraphics();
		boolean loading = true;
		long tick;
		// int counter = 0;
		// boolean loadingonce = false;
		m_counter = 0;
		String[] tips = mergeStrings();
		int dex = Tools.getRandom(0, tips.length - 1); // 随机下标
		s_randomLoadingString = Tools.splitString(tips[dex], AbstractGameScreen.s_font, '^', 180);
		tips = null;
		while (loading) {
			tick = System.currentTimeMillis() + GameManager.FRAME_INTERVAL;
			AbstractGameScreen.updateKeyBegin();
			// ResourceManager.getInstance().removeAllResource(GameManager.getInstance().m_resource_scene);
			// ResourceManager.getInstance().loadResource(GameManager.getInstance().m_resource_scene,
			// GameManager.getInstance().m_sceneResList);
			GameManager.getInstance().debugLogLogic();
			GameManager.getInstance().debugLogDraw(g);
			if (m_loading_screen.loading()) {

				if (m_counter >= 90 && m_counter < 99) {
					m_counter++;
				}
				//Tools.debugPrintln("缺失数量=" + ResourceManager.getInstance().getResMissSize());
				if (m_counter >= 99 && GameManager.getInstance().m_scene != null) {
					m_scene.checkLoadFinished();
					if (m_scene.m_loadFinished && m_scene.m_bg.m_loadFinished) {
						m_counter = 100;
						// UiManager.getInstance().removeAllWindowFromWindowList();
						if (s_instance.m_showData == null)
							s_instance.m_showData = (UIShowData)UIWindowFactory
							         .createWindow(UIWindowFactory.WINDOW_SHOWDATA);
						if (s_instance.m_task_window == null)
							s_instance.m_task_window = (UITaskWindow) UIWindowFactory
									.createWindow(UIWindowFactory.WINDOW_ID_TASK);
						if (s_instance.m_npc_window == null)
							s_instance.m_npc_window = (UINPCWindow) UIWindowFactory
									.createWindow(UIWindowFactory.WINDOW_ID_NPC);
						if (s_instance.m_life_skills_window == null)
							s_instance.m_life_skills_window = (UILifeSkillsWindow) UIWindowFactory
									.createWindow(UIWindowFactory.WINDOW_ID_LIFESKILLS);
						if (s_instance.m_family_window == null)
							s_instance.m_family_window = (UIFamilyWindow) UIWindowFactory
									.createWindow(UIWindowFactory.WINDOW_ID_FAMILY);

						GameManager.getInstance().m_scene.m_id = GameManager.getInstance().m_stage;
						GameManager.getInstance().m_scene.m_name = GameManager.getInstance().m_map_name;
						GameManager.getInstance().setGameStatus(GameManager.GS_GAME);
						m_scene.init();
						loading = false;
						m_loading_screen.m_progress = m_loading_screen.SCENE_INFORMATION;
					}
				}
			}
			else {
				if (ResourceManager.getInstance().m_load_percent > 0
						&& ResourceManager.getInstance().m_load_percent < 100) {
					m_counter = m_counter + ResourceManager.getInstance().m_load_percent * 35 / 100;
					if (m_counter > 65) {
						m_counter = 65;
					}
				}
			}
			drawLoadingBar(g, m_counter);
			if (++m_loading_timer > 1000000) {
				m_loading_timer = 0;
			}
			keepConnectionAlive();
			m_screen.flush();
			AbstractGameScreen.updateKeyEnd();
			while (tick > System.currentTimeMillis()) {
				Thread.yield();
			}
		}
	}

	private static String[] s_randomLoadingString = null; // 加载界面切割后的字符串
	// #if screen == "640360"
	  private static int m_loadingbar_string_h=30;
	  private static int m_loadingbar_hint=10;
	// #else
//	private static int m_loadingbar_string_h = AbstractGameScreen.SCREEN_HEIGHT / 2;
//	private static int m_loadingbar_hint = 0;

	// #endif
	/**
	 * 绘制場景进度条
	 *
	 * @param g
	 * @param counter
	 */
	public static void drawLoadingBar(Graphics g, int counter)
	{
		Font m_font = AbstractGameScreen.s_font;
		// if (counter == 0) { // 画随机字符串
		// Random r = new Random();
		// int dex = r.nextInt(LOADING_TIPS.length); // 随机下标
		// s_randomLoadingString = Tools.splitString(LOADING_TIPS[dex], m_font,
		// '^', 180);
		// }
		if (counter < 0 || counter > 100)
			return;

		g.setColor(0x0);
		g.setClip(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
		g.fillRect(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
		g.setColor(0xffffff);
		for (int j = 0; j < s_randomLoadingString.length; j++) {
			g.drawString(s_randomLoadingString[j], AbstractGameScreen.SCREEN_WIDTH / 2, m_loadingbar_string_h
					+ m_font.getHeight() * j, Tools.HCENTER_TOP);
		}
		// ActorRole role = GameManager.getInstance().m_role;
		// if (role != null) {
		// if (counter == 0) {
		// role.setAction(ActorRole.ACTION_ATTACK2, true, true);
		// }
		// role.m_posX = 40;
		// role.m_posY = 200;
		// role.draw(g, 0, 0);
		// role.nextFrame();
		// }

		g.drawImage(
				GameScene.s_img_loadingFrame,
				AbstractGameScreen.SCREEN_WIDTH / 2,
				(AbstractGameScreen.SCREEN_HEIGHT - GameScene.s_img_loadingFrame.getHeight() - AbstractGameScreen.FONT_H)
						+ m_loadingbar_hint, Tools.HCENTER_TOP);
		g.drawImage(GameScene.s_img_loadingGuang,
				(AbstractGameScreen.SCREEN_WIDTH - 206) / 2 + 7 + 180 * counter / 100,
				(AbstractGameScreen.SCREEN_HEIGHT
						- GameScene.s_img_loadingFrame.getHeight() - AbstractGameScreen.FONT_H + 16)
						+ m_loadingbar_hint, Tools.HCENTER_VCENTER);

		g.setColor(COLOR_LOADINGBAR);
		g.fillRect((AbstractGameScreen.SCREEN_WIDTH - 206) / 2 + 7, (AbstractGameScreen.SCREEN_HEIGHT
				- GameScene.s_img_loadingFrame.getHeight() - AbstractGameScreen.FONT_H + 15)
				+ m_loadingbar_hint, 180 * counter / 100, 3);

		g.setColor(Tools.WHITE);
		String temp = "";
		String text = "";
		int w = 0;
		if (counter < 10) {
			text = LOADING_DESCRIBE[0];
		}
		else if (counter < 30) {
			text = LOADING_DESCRIBE[1];
		}
		else if (counter < 80) {
			text = LOADING_DESCRIBE[2];
		}
		else if (counter <= 100) {
			text = LOADING_DESCRIBE[3];
		}
		int timer = (m_loading_timer % 24) / 6;
		temp = text.substring(0, text.length() - (3 - timer));
		w = AbstractGameScreen.s_font.stringWidth(text.substring(0, text.length() - 3)) >> 1;
		g.drawString("(" + counter + ")" + temp, (AbstractGameScreen.SCREEN_WIDTH >> 1) - w,
				AbstractGameScreen.SCREEN_HEIGHT, Tools.LEFT_BOTTOM);
	}

	public boolean m_test_running;
	public boolean m_pause_run = false;// 暂停线程

	public void runTest()
	{
		Graphics g = m_screen.getGraphics();
		// Animation anim_test = new Animation();
		ResHead head = new ResHead();

		GameScene actor_test = new GameScene();
		head.m_type = ObjectAdapter.RESOURCE_TYPE_SCENE;
		head.m_url = "/scene/stest.scn";
		actor_test = (GameScene) (ResourceManager.getInstance().loadResource(m_resource_scene, head));
		actor_test.init();
		long tick;
		// int counter = 0;
		m_test_running = true;
		while (m_test_running) {
			tick = System.currentTimeMillis() + GameManager.FRAME_INTERVAL;
			AbstractGameScreen.updateKeyBegin();
			g.setClip(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
			g.setColor(0xffffff);
			g.fillRect(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);

			actor_test.updateCamera();
			actor_test.updateActorList();
			actor_test.updateLogic();
			actor_test.draw(g);

			AbstractGameScreen.updateKeyEnd();
			m_screen.flush();
			// counter++;
			while (tick > System.currentTimeMillis()) {
				Thread.yield();
			}
		}
	}

	public void runScene()
	{

	}

	private static long s_curTime;

	/**
	 * 等待一帧
	 */
	public static void waitOneFrame()
	{
		try {
			int wait = Tools.limit((int) (60 - (System.currentTimeMillis() - s_curTime)), FRAME_INTERVAL, 0);
			Thread.sleep(wait);
			s_curTime = System.currentTimeMillis();
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	/**
	 * 线程休眠指定的时间
	 *
	 * @param time
	 */
	public static void waitAnyTime(long time)
	{
		time = time + System.currentTimeMillis();
		while (time > System.currentTimeMillis()) {
			Thread.yield();
		}
	}

	/**
	 * 线程休眠直到按下任意键
	 */
	public static void waitAnyKey()
	{
		AbstractGameScreen.updateKeyEnd();
		AbstractGameScreen.updateKeyBegin();
		while (!AbstractGameScreen.anyKeyPressed()) {
			AbstractGameScreen.updateKeyBegin();
			Thread.yield();
			AbstractGameScreen.updateKeyEnd();
			waitAnyTime(FRAME_INTERVAL);
			s_instance.keepConnectionAlive();
		}
	}

	/**
	 * 线程休眠直到按下任意键或者到了指定的时间
	 */
	public static void waitAnyKey(long time)
	{
		AbstractGameScreen.updateKeyEnd();
		AbstractGameScreen.updateKeyBegin();
		time = time + System.currentTimeMillis();
		while (!AbstractGameScreen.anyKeyPressed() && System.currentTimeMillis() < time) {
			AbstractGameScreen.updateKeyBegin();
			Thread.yield();
			AbstractGameScreen.updateKeyEnd();
			waitAnyTime(FRAME_INTERVAL);
			s_instance.keepConnectionAlive();
		}
	}

	/**
	 * 线程休眠直到按下特定键或者到了指定的时间
	 *
	 * @param time
	 * long
	 * @param key
	 * int
	 * @return boolean 是否按了特定键
	 */
	public static boolean waitAnyKey(long time, int key)
	{
		AbstractGameScreen.updateKeyEnd();
		AbstractGameScreen.updateKeyBegin();
		time = time + System.currentTimeMillis();
		while (System.currentTimeMillis() < time) {
			AbstractGameScreen.updateKeyBegin();
			if (key > 0 && AbstractGameScreen.haveKeyPressed(key)) {
				AbstractGameScreen.updateKeyEnd();
				return true;
			}
			Thread.yield();
			AbstractGameScreen.updateKeyEnd();
			waitAnyTime(FRAME_INTERVAL);
			s_instance.keepConnectionAlive();
		}
		return false;
	}

	private Thread m_thread;

	/**
	 * 启动线程
	 */
	public void startThread()
	{
		m_thread = new Thread(this);
		// m_thread.setPriority(Thread.MAX_PRIORITY);
		m_thread.start();
	}

	// ////////////////////////////////////////
	// // network

	public void recvErrSystemMessage(byte[] body)
	{
		ByteArrayInputStream bais = null;
		DataInputStream dis = null;
		try {
			bais = new ByteArrayInputStream(body);
			dis = new DataInputStream(bais);
			if (body != null) {
				int protocolId = dis.readInt();
				String info = dis.readUTF();
				Tools.debugPrintln("recvErrSystemMessage : id = " + protocolId + " infos = " + info);
				// addSystemInfo(type, content) ;
			}
		}
		catch (Exception e) {
		}
		finally {
			GameManager.getInstance().m_game_message.unlockNetwork();
			try {
				dis.close();
			}
			catch (IOException ex) {
				Tools.debug(ex);
			}
			try {
				bais.close();
			}
			catch (IOException ex) {
				Tools.debug(ex);
			}
			dis = null;
			bais = null;
		}
	}

	/**
	 * 处理消息
	 */
	public boolean recvMessage(int type, byte[] body)
	{
		int order = BaseConnection.s_perseOrderID;
//		Log.d("xltest", "recvMessage, ="+order);
		if (order == GameProtocol.S_RMB_GET_ITEM_DOWN) {
//		    Log.d("xltest", "@##$$%%%$$#$recvMessage, ="+order);
		}
		// 连接异常
		if (type == GameProtocol.CONNECTION_BROKEN) {
			Tools.debugPrintln("网络连接异常!");
			dealForConnectionException();
			return false;
		}
		// 数据为空
		if (body == null)
			return false;
		// 处理数据
		switch (order) {
			case GameProtocol.CS_ERR_MESSAGE:
				recvErrSystemMessage(body);
				break;
			case GameProtocol.SC_HEARTBEAT: {
				dealWorldTimer(body);
				break;
			}
			case GameProtocol.C_DEFAULT: {
				dealWorldTimer_old(body);
				break;
			}
			case GameProtocol.SC_RECEIVE_RESOURCE: {
				recvResource(body);
				break;
			}
			case GameProtocol.SC_JUMP_DOWNLOAD: {
				recvJumpForDownload(body);
				break;
			}
			default: {
				switch (m_gameStatus) {
					case GS_USER:
						m_user_screen.recvMessage(type, body);
						break;
					case GS_GAME:
						m_scene.recvMessage(type, body);
						break;
					case GS_LOADING:
						Tools.debugPrintln("recv m_gameStatus : " + m_gameStatus);
						m_loading_screen.recvMessage(type, body);
						// if (m_scene == null) {
						// Tools.debugPrintln("场景为空,指令号：" +
						// BaseConnection2.s_orderID);
						// }
						// m_scene.recvMessage(type, body);
						break;
				}
				break;
			}
		}
		// 处理过需要等待的指令后，将变量置成-1
		if (m_waitingCommandId == BaseConnection.s_perseOrderID) {
			m_waitingCommandId = -1;
		}
		return false;
	}

	private boolean m_isDeal = false;

	/**
	 * 处理连接异常
	 */
	public void dealForConnectionException()
	{
		if (!m_isDeal) {
			m_isDeal = true;
			m_game_message.unlockNetwork();
			s_isControlledByUi = true;
			final UIMessageBox messageBox = (UIMessageBox) UIManager.getInstance().createWindow(
					UIWindowFactory.WINDOW_MESSAGEBOX);
			messageBox.setMessage("网络连接被断开!");
			messageBox.addListener(new UIListener() {
				public void actionPerformed()
				{
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
							|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						Tools.debugPrintln("网络连接断开按键监听!");
						UIManager.getInstance().removeAllWindows();
						if (m_scene != null) {
							m_scene.m_isRunning = false;
						}
						if (s_instance.m_user_screen == null) {
							s_instance.m_user_screen = new UserScreen((GameScreen) s_instance.m_screen);
						}
						if (s_instance.m_loading_screen != null) {
							s_instance.m_loading_screen.m_progress = 0;
						}
						if (m_role != null) {
							m_role.clearPathfinding();
						}
						m_game_message.unlockNetwork();
						s_instance.m_user_screen.setNextState(UserScreen.STATE_LOADING);
						setGameStatus(GameManager.GS_USER);
						closeConnection();
						m_connection = null;
						s_isControlledByUi = false;
						m_isDeal = false;
					}
				}
			});
		}
	}

	public static long[][] s_delaysTimes = new long[TcpConnection.TRANSNUM][2];
	public static int s_delaysTimeNum = -1;

	public void delaysTime(long a,long b){
		if( ++s_delaysTimeNum < TcpConnection.TRANSNUM ){
			s_delaysTimes[s_delaysTimeNum][0] = a;
			s_delaysTimes[s_delaysTimeNum][1] = b;
			Tools.debugPrintln("s_delaysTimes["+s_delaysTimeNum+"][0]="+s_delaysTimes[s_delaysTimeNum][0]);
			Tools.debugPrintln("s_delaysTimes["+s_delaysTimeNum+"][1]="+s_delaysTimes[s_delaysTimeNum][1]);
		}
		Tools.debugPrintln("GameMange s_delaysTimeNum="+s_delaysTimeNum);
	}
	/**
	 * 处理世界时间
	 *
	 * @param body
	 */
	public void dealWorldTimer(byte[] body)
	{
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);
			long lastTime = dis.readLong();
			s_worldTimeServer = dis.readLong();
			long curTime = System.currentTimeMillis();
			s_worldTimeDelay = s_worldTimeServer - curTime + (curTime - lastTime) / 2;
			delaysTime(lastTime, curTime);
			//
			// Date data1 = new Date(s_worldTimeServer);
			// Date data2 = new Date(curTime);
			//
			// System.out.println("server time:" + data1.toString());
			// System.out.println("client time:" + data2.toString());

			dis.close();
			bais.close();
			dis = null;
			bais = null;
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	/**
	 * 处理世界时间
	 *
	 * @param body
	 */
	public void dealWorldTimer_old(byte[] body)
	{
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);
			s_worldTimeServer = dis.readLong();
			s_worldTimeDelay = s_worldTimeServer - System.currentTimeMillis();

			dis.close();
			bais.close();
			dis = null;
			bais = null;
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	public void recvJumpForDownload(byte[] body)
	{
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);

			String info = dis.readUTF();
			openHyperWindow(info);

			bais.close();
			dis.close();
		}
		catch (IOException ex) {
			if (body != null) {
				for (int i = 0; i < body.length; i++) {
					Tools.debugPrintln("body[" + i + "]=" + body[i]);
				}
			}
			Tools.debug(ex);
		}
	}

	public void openHyperWindow(String info)
	{
		final UIMessageBox box = (UIMessageBox) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MESSAGEBOX);
		box.setMessage(info);
		box.addListener(new UIListener() {

			private AbsHyperLinker hyperLinker = box.getHyperLinker();

			public void actionPerformed()
			{
				if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
						|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
					if (hyperLinker == null) {
						UIManager.getInstance().removeWindow(box);
						return;
					}
					int index = hyperLinker.actionOnFire();
					char type = hyperLinker.getHyperLinkTypes()[index];
					final String id = hyperLinker.getHyperLinkIds()[index];
					switch (type) {
						case AbsHyperLinker.URL_DOWNLOAD:
							GameMIDlet.s_JumpUrl = hyperLinker.getHyperLinkContents()[index] ;
							switch (GameManager.getInstance().m_gameStatus) {
								case GS_GAME:
									if (m_scene != null) {
										m_scene.exitGame();
									}
									break;
								case GS_USER:
									if (m_user_screen != null) {
										m_user_screen.exitGame();
									}
									break;
							}
							break;
					}
					UIManager.getInstance().removeWindow(box);
				}
				else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
					UIManager.getInstance().removeWindow(box);
				}
				else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)
						|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT)) {
					if (hyperLinker == null) {
						return;
					}
					hyperLinker.actionOnUp();
				}
				else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT)
						|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT)) {
					if (hyperLinker == null) {
						return;
					}
					hyperLinker.actionOnDown();
				}
			}
		});
	}

	// ////////////////////////////////////////////////////////////////////
	// // 公告相关
	public ArrayList m_announcement = new ArrayList();
	public int m_curAnnounceColor; // 字体颜色
	public String m_curAnnounceContent; // 公告内容
	public boolean m_isAnnounceShowing; // 是否正在显示消息
	public int m_curAnnounceFrameCounter; // 当前消息显示帧数
	public int m_curAnnounceContentWidth; // 当前消息内容像素宽度

	/**
	 * 添加系统消息
	 *
	 * @param content
	 * @param color
	 */
	public void addAnnounce(String content, int color)
	{
		StringBuffer message = new StringBuffer(content);
		message.append('$');
		message.append(color);
		m_announcement.addElement(message.toString());
	}

	/**
	 * 初始化将要显示的系统消息
	 */
	public void initAnnounce()
	{
		String message = (String) m_announcement.elementAt(0);
		String[] info = Tools.splitString(message, '$');
		m_curAnnounceColor = Integer.parseInt(info[1]);
		m_curAnnounceContent = info[0];
		m_curAnnounceContentWidth = AbstractGameScreen.s_font.stringWidth(info[0]);
		m_curAnnounceFrameCounter = 0;
		m_isAnnounceShowing = true;
	}

	/**
	 * 显示系统消息
	 */
	public void showAnnounce(Graphics g)
	{
		if (m_isAnnounceShowing
				&& -m_curAnnounceFrameCounter * 2 + AbstractGameScreen.SCREEN_WIDTH + m_curAnnounceContentWidth > 0) {
			g.setColor(m_curAnnounceColor);
			// paint
		}
		else {
			m_isAnnounceShowing = false;
			m_announcement.removeElementAt(0);
			if (m_announcement.size() > 0) {
				initAnnounce();
			}
		}
		m_curAnnounceFrameCounter++;
	}

	// // 公告相关
	// ////////////////////////////////////////////////////////////////////

	// ////////////////////////////////////////////////////////////////////
	// // 弹出消息框消息
	public ArrayList m_messages = new ArrayList();
	public UIMessageBox m_msg_dialog;
	public int m_message_life;

	/**
	 * 添加消息
	 *
	 * @param messsage
	 */
	public void addMessage(String messsage)
	{
		if (messsage == null) {
			return;
		}
		int size = m_messages.size();
		if (size > 1) {// 当前具有提示信息
			String temp = (String) m_messages.elementAt(size - 1);
			if (messsage.equals(temp)) {
				return;// 屏蔽多个消息完全一样的情况
			}
		}
		m_messages.addElement(messsage);
	}

	/**
	 * 执行消息
	 */
	public void runMessage()
	{
		showMessage(m_screen.getGraphics());
		if (m_messages.size() > 0 && m_message_life == 0) {
			String content = (String) m_messages.elementAt(0);
			m_messages.removeElementAt(0);
			m_msg_dialog = (UIMessageBox) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_MESSAGEBOX);
			m_msg_dialog.setFocusable(false);// 需要加此标示,
			m_msg_dialog.setMessage(null, null, null, content);
			m_msg_dialog.addListener(new UIListener() {
				private int time;

				public void actionPerformed()
				{
					time++;
					if (time == 10) {
						remove();
						return;
					}
					if (AbstractGameScreen.anyKeyPressed()) {
						remove();
					}
				}

				private void remove()
				{
					UIManager.getInstance().removeWindow(m_msg_dialog);
					m_msg_dialog = null;
				}
			});
			m_message_life = 10;
		}
	}

	/**
	 * 移除消息
	 */
	public void removeMessage()
	{
		if (m_messages.size() > 0) {
			m_messages.removeElementAt(0);
		}
	}

	/**
	 * 绘制消息
	 *
	 * @param g
	 */
	public void showMessage(Graphics g)
	{
		if (m_message_life > 0) {
			m_message_life--;
			if (m_msg_dialog != null) {
				m_msg_dialog.paintContent(g);
			}
		}
	}

	// ////////////////////////////////////////////////////////////////////
	// // 系统消息相关

	private final int NONE_PIC = -1000;
	private final int END_PIC = -2;
	public ArrayList m_sys_message;
	private int m_relX_sysMessage = AbstractGameScreen.SCREEN_WIDTH;
	private int m_relX_pic = NONE_PIC;
	private int m_w_sysMessage;
	private final int Y_SYSMESSAGE = AbstractGameScreen.SCREEN_WIDTH / 5;
	private final int H_SYSMESSAGE = AbstractGameScreen.FONT_H + 6;
	//chicheng 01 chouhen 02 fennu 03 ganji 04
	private final int[] COLOR_SYS = new int[] { 0xaa087879, 0xaaEE2672, 0xaaff0000, 0xaa000000, 0xaa0000ff };
	private int m_type_sys;
	private int m_color_sys = COLOR_SYS[0];

	/**
	 * 运行系统消息 2012-3-12 上午10:13:53 venizeng
	 */
	public void runSysMessage()
	{
		if (m_sys_message == null) {
			return;
		}
		if (m_sys_message.size() == 0) {
			return;
		}
		if (m_w_sysMessage == 0) {
			String temp = (String) m_sys_message.elementAt(0);
			if (temp == null) {
				return;
			}
			m_w_sysMessage = AbstractGameScreen.s_font.stringWidth(AbsHyperLinker.removeHyper(temp)) + 2;
			//
			int num_pic = AbsHyperLinker.getPicNum(temp);//计算图片的数目
			m_w_sysMessage += num_pic * 16;//图片的宽度
			//
			m_type_sys = getSysMessageType(temp);
			if (m_type_sys == -1) {
				m_color_sys = COLOR_SYS[0];
				m_relX_pic = NONE_PIC;
			}
			else if (m_type_sys == 0) {
				m_relX_pic = NONE_PIC;
				m_color_sys = COLOR_SYS[m_type_sys];
				m_relX_pic = NONE_PIC;
			}
			else {
				m_relX_pic = (AbstractGameScreen.SCREEN_WIDTH >> 1) - UIManager.IMAGE_BODER_SPEAKER_MESSAGE.getWidth();
				m_color_sys = COLOR_SYS[m_type_sys];
			}
			temp = getSysMessage(temp, m_type_sys);
			if (AbsHyperLinker.isHyperLink(temp)) {//超链接形式
				AbsHyperLinker hyperLinker = AbsHyperLinker.createHyperLinker(temp, m_w_sysMessage, H_SYSMESSAGE);
				m_sys_message.setElementAt(hyperLinker, 0);
			}
			else {
				m_sys_message.setElementAt(temp, 0);
			}
		}

		runCommonSys(m_sys_message.elementAt(0));
	}

	private void runCommonSys(Object temp)
	{
		if (m_relX_pic == NONE_PIC) {
			m_relX_sysMessage -= 5;
			showSysMessage(m_screen.getGraphics(), temp);
			if (m_relX_sysMessage <= -m_w_sysMessage) {
				removeSysMessage();
			}
		}
		else {
			if (m_relX_pic > END_PIC) {// 移动两边的图片o
				m_relX_pic -= 4;
			}
			else {
				m_relX_pic = END_PIC;
			}
			showSysMessage(m_screen.getGraphics(), temp);
			if (m_relX_pic == END_PIC) {
				m_relX_sysMessage -= 3;
				if (m_relX_sysMessage <= -m_w_sysMessage) {
					removeSysMessage();
				}
			}
		}
	}

	/**
	 * 显示系统消息 2012-3-12 上午10:14:11 venizeng
	 */
	public void showSysMessage(Graphics g, Object temp)
	{
// 绘制文字
		int clipX = g.getClipX();
		int clipY = g.getClipY();
		int clipW = g.getClipWidth();
		int clipH = g.getClipHeight();
		g.setClip(0, 0, AbstractGameScreen.SCREEN_WIDTH, AbstractGameScreen.SCREEN_HEIGHT);
		int IW = m_relX_pic == NONE_PIC ? 0 : 2;
		int RELX = 6 + IW;
		if (m_relX_pic > NONE_PIC) {// 喇叭喊话
			// 绘制背景框
			int RX = m_relX_pic + RELX;
//			UITools.fillContentRect(g, RX, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH - (RX << 1), H_SYSMESSAGE, m_color_sys);
			UITools.drawFillRectAlpha(g, RX, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH - (RX << 1), H_SYSMESSAGE,
					m_color_sys);
			int[] colors = UIManager.getColorsSubcoatBorder();
			for (int i = 0, length = colors.length; i < length; i++) {
				UITools.drawRect(g, RX, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH - (RX << 1), H_SYSMESSAGE,
						colors[i], i);
			}
			int Y = UITools.IH_RECT_CONTENT + 5;
			Tools.drawRegion(g, UIManager.IMAGE_BODER_SPEAKER_MESSAGE, m_relX_pic, Y_SYSMESSAGE + H_SYSMESSAGE + Y,
					Tools.TRANS_HV, Tools.LEFT_BOTTOM);
			Tools.drawRegion(g, UIManager.IMAGE_BODER_SPEAKER_MESSAGE, AbstractGameScreen.SCREEN_WIDTH - m_relX_pic,
					Y_SYSMESSAGE - Y, Tools.TRANS_NONE,
					Tools.RIGHT_TOP);
		}
		else {
			// 绘制背景框
//			UITools.fillContentRect(g, 0, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH, H_SYSMESSAGE, m_color_sys);
			UITools.drawFillRectAlpha(g, 0, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH, H_SYSMESSAGE, m_color_sys);
			int[] colors = UIManager.getColorsSubcoatBorder();
			for (int i = 0, length = colors.length; i < length; i++) {
				UITools.drawRect(g, 0, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH, H_SYSMESSAGE, colors[i], i);
			}
		}
		g.setClip(RELX, Y_SYSMESSAGE, AbstractGameScreen.SCREEN_WIDTH - (RELX << 1), H_SYSMESSAGE);
		RELX += 4;
		int tempX = m_relX_sysMessage;
		int tempY = Y_SYSMESSAGE + UIManager.getColorsSubcoatBorder().length;
		if (temp instanceof String) {
			g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
			g.drawString((String) temp, tempX, tempY, 0);
		}
		else {
			AbsHyperLinker hyperLinker = (AbsHyperLinker) temp;
			hyperLinker.paintInRect(g, tempX, tempY);
		}
		g.setClip(clipX, clipY, clipW, clipH);
	}

	/**
	 * 加入到系统消息队列中，显示在场景及UI层之上
	 */
	public void addSysMessage(String content)
	{
		if (m_sys_message == null) {
			m_sys_message = new ArrayList(10, 5);
		}
		m_sys_message.addElement(content);
	}

	private int getSysMessageType(String content)
	{
		int type = -1;
		try {
			type = Integer.parseInt(content.substring(0, 2));
		}
		catch (Exception e) {
		}
		if (type < -1 || type >= COLOR_SYS.length) {
			return -1;
		}
		return type;
	}

	private String getSysMessage(String content, int type)
	{
		if (type == -1) {
			return content;
		}
		else {
			return content.substring(2, content.length());
		}
	}

	public void removeSysMessage()
	{
		if (m_sys_message == null) {
			return;
		}
		if (m_sys_message.size() > 0) {
			m_sys_message.removeElementAt(0);
		}
		// 清零
		m_w_sysMessage = 0;
		m_relX_sysMessage = AbstractGameScreen.SCREEN_WIDTH;
	}

	// // 弹出消息框消息
	// ////////////////////////////////////////////////////////////////////

	public static final int SYSTEM_INFO_TYPE_A = 0;
	public static final int SYSTEM_INFO_TYPE_B = 1;
	public static final int SYSTEM_INFO_TYPE_C = 2;
	public static final int SYSTEM_INFO_TYPE_D = 3;
	public static final int SYSTEM_INFO_TYPE_E = 4;// 系统消息,悬停在UI与场景之上
	public static final int SYSTEM_INFO_TYPE_F = 5;

	/**
	 * 添加各种系统信息
	 *
	 * @param type
	 * @param content
	 */
	public void addSystemInfo(int type, String content)
	{
		switch (type) {
			case SYSTEM_INFO_TYPE_A:
				if (m_scene != null) {
					((GameScene) m_scene).addMessage(content, Tools.RED, Tools.BLACK);
				}
				break;
			case SYSTEM_INFO_TYPE_B:// 点击即消失,并随时间变化
				addMessage(content);
				break;
			case SYSTEM_INFO_TYPE_C:
				// ChatItem item = ChatItem.createChatItem(ChatItem.TYPE_XI, -1,
				// "系", "", content);
				ChatItem item = ChatItem.createChatItem(ChatItem.TYPE_XI, -1, "", "", content);
				m_role.addToChat(item);
				break;
			case SYSTEM_INFO_TYPE_D:// 点击即消失,不会随时间变化
				if (m_scene != null) {
					final UIMessageBox alertBox = (UIMessageBox) UIManager.getInstance().createWindow(
							UIWindowFactory.WINDOW_MESSAGEBOX);
					alertBox.setMessage(content);
					alertBox.addListener(new UIListener() {
						public void actionPerformed()
						{
							if (AbstractGameScreen.anyKeyPressed()) {
								UIManager.getInstance().removeWindow(alertBox);
							}
						}
					});
				}
				break;
			case SYSTEM_INFO_TYPE_E:
				addSysMessage(content);
				break;
			case SYSTEM_INFO_TYPE_F:
				break;
		}
	}

	// ////////////////////////////////////////////////////////////////////
	// // RMS相关

	public static byte[] s_curGameData; // 储存游戏数据介质
	public static final String RMS_NAME_USER = "User_v1.0";// 默认账号保存
	public static final int RMS_INDEX_USER = 0;

	// 操作方式
	public static final int R_READ = 0;
	public static final int R_WRITE = 1;
	public static final int R_CLEAR = 2;

	public static final int GAMERECORD_MAXITEM = 1;

	public static final void initUserRMSData()
	{
		try {
			RecordStore recStore = RecordStore.openRecordStore(RMS_NAME_USER, true);
			RecordEnumeration recEnum = recStore.enumerateRecords(null, null, false);

			if (!recEnum.hasNextElement()) {
				for (int i = 0; i < GAMERECORD_MAXITEM; i++) {
					recStore.addRecord(null, 0, 0);
				}
			}

			recEnum.destroy();
			recStore.closeRecordStore();
			recStore = null;
			recEnum = null;

		}
		catch (Exception e) {
			// System.out.println("Exception: error: savedocument() "+e);
		}
	}

	/**
	 * RMS管理 (游戏数据)
	 *
	 * @param id
	 * int 记录id
	 * @param option
	 * int 操作方式
	 */
	public static void manageUserRMSData(int id, int option)
	{
		try {
			RecordStore recStore = RecordStore.openRecordStore(RMS_NAME_USER, true);
			RecordEnumeration recEnum = recStore.enumerateRecords(null, null, false);
			int rmsAmount = recStore.getSizeAvailable();
			long memAmount = Runtime.getRuntime().totalMemory();
			Tools.debugPrintln("RMS PC: " + recStore.getSizeAvailable());
			Tools.debugPrintln("MEM PC: " + Runtime.getRuntime().totalMemory());
			if (!Tools.EMULATOR_OPEN) {
				if (Tools.isEmulator(rmsAmount, memAmount)) {
					recEnum.destroy();
					recStore.closeRecordStore();
					recStore = null;
					recEnum = null;
					s_instance.m_test_running = false;
					s_isRunning = false;
					return;
				}
			}
			Tools.debugPrintln("manage");
			while (recEnum.hasNextElement()) {
				int recID = recEnum.nextRecordId();
				Tools.debugPrintln("manage rms : " + recID);
				if (recID == (id + 1)) {
					if (option == R_READ) {
						s_curGameData = recStore.getRecord(recID);
						Tools.debugPrintln("manage rms read : " + s_curGameData);
						if (s_curGameData != null)
							loadUserRMSData();
						s_curGameData = null;
					}
					else if (option == R_WRITE) {
						setUserRMSData();
						recStore.setRecord(recID, s_curGameData, 0, s_curGameData.length);
						s_curGameData = null;
					}
					else if (option == R_CLEAR) {
						s_curGameData = null;
						recStore.setRecord(recID, s_curGameData, 0, 0);
					}
				}

			}
			recEnum.destroy();
			recStore.closeRecordStore();
			recStore = null;
			recEnum = null;
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	/**
	 * 判断某存档是否存在
	 *
	 * @param mode
	 * int
	 * @return boolean
	 */
	public static boolean canLoadUserRMSData(int id)
	{
		try {
			RecordStore recStore = RecordStore.openRecordStore(RMS_NAME_USER, true);
			RecordEnumeration recEnum = recStore.enumerateRecords(null, null, false);

			while (recEnum.hasNextElement()) {
				int recID = recEnum.nextRecordId();
				if (recID == (id + 1)) {
					s_curGameData = null;
					s_curGameData = recStore.getRecord(recID);
					if (s_curGameData == null)
						return false;
					else
						return true;
				}
			}

			recEnum.destroy();
			recStore.closeRecordStore();
			recStore = null;
			recEnum = null;
			return false;
		}
		catch (Exception ex) {
			Tools.debug(ex);
			return false;
		}
	}

	/**
	 * 读取游戏数据
	 */
	public static void loadUserRMSData()
	{
		try {
			DataInputStream dis = new DataInputStream(new ByteArrayInputStream(s_curGameData));
			// 在这里载入相关数据

			UserScreen.m_save_name = dis.readBoolean();
			Tools.debugPrintln("rms read m_save_name : " + UserScreen.m_save_name);
			if (UserScreen.m_save_name) {
				UserScreen.m_login_name = dis.readUTF();
				UserScreen.m_login_password = dis.readUTF();
				Tools.debugPrintln("rms read m_login_name : " + UserScreen.m_login_name);
				Tools.debugPrintln("rms read m_login_password : " + UserScreen.m_login_password);
			}
			else {
				Tools.debugPrintln("rms read m_login_name : " + dis.readUTF());
				Tools.debugPrintln("rms read m_login_password : " + dis.readUTF());
			}
			UserScreen.m_user_id = dis.readLong();
			Tools.debugPrintln("rms read m_user_id : " + UserScreen.m_user_id);
			dis.close();
			dis = null;
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	/**
	 * 储存游戏数据
	 */
	public static void setUserRMSData()
	{
		try {
			ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(byteOutputStream);
			// 在这里写入相关数据
			dos.writeBoolean(UserScreen.m_save_name);
			dos.writeUTF(UserScreen.m_login_name);
			dos.writeUTF(UserScreen.m_login_password);
			dos.writeLong(UserScreen.m_user_id);
			Tools.debugPrintln("rms write m_save_name : " + UserScreen.m_save_name);
			Tools.debugPrintln("rms write m_login_name : " + UserScreen.m_login_name);
			Tools.debugPrintln("rms write m_login_password : " + UserScreen.m_login_password);
			Tools.debugPrintln("rms write m_user_id : " + UserScreen.m_user_id);
			dos.flush();
			s_curGameData = byteOutputStream.toByteArray();
			dos.close();
			byteOutputStream.close();
			dos = null;
			byteOutputStream = null;
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	// // RMS相关
	// ////////////////////////////////////////////////////////////////////

	// ////////////////////////////////////////////////////////////////////
	// // 资源相关
	public Resource m_resource_scene; // 游戏场景资源，例如：地图，场景NPC，怪物， 战斗光效等
	public Resource m_resource_static; // 游戏静态资源，例如：角色，UI等

	/**
	 * 请求单个资源
	 *
	 * @param head
	 */
	public void requestResource(ResHead head)
	{
		if (head != null) {
			Tools.debugPrintln("请求单个缺失资源：" + GameProtocol.CS_REQUEST_RESOURCE);
			m_game_message.sendRequestResource(head);
		}
	}

	/**
	 * 请求多个资源
	 *
	 * @param heads
	 */
	public void requestResource(Vector heads)
	{
		if (heads.size() > 0) {
			Tools.debugPrintln("请求缺失资源：" + GameProtocol.CS_REQUEST_RESOURCE + ";缺失资源个数=" + heads.size());
			m_game_message.sendRequestResource(heads);
		}
	}

	public void recvResource(byte[] body)
	{
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);
			ResHead head;
			Serializeable inst;
			int num = dis.readShort();
			Tools.debugPrintln("接收缺失资源：" + GameProtocol.SC_RECEIVE_RESOURCE);
			for (int i = 0; i < num; i++) {
				byte a = dis.readByte();
				String b = dis.readUTF();
				Tools.debugPrintln("接收到缺失资源名：" + b);
				head = new ResHead(a, b, 1);
				int dataLength = dis.readInt();
				byte[] data = new byte[dataLength];
				dis.read(data);
				// 移除缺失资源
				ResourceManager.getInstance().removeMissRes(head);
				// 解析数据包并且进行相应的持久化处理
				ResourceManager.getInstance().downloadResource(head, data);
				try {
					// 更新资源
					if (m_gameStatus == GS_USER) {
						if (GameManager.getInstance().m_user_screen.m_user_resource.containMissRes(head)) {
							inst = ResourceManager.getInstance().loadResource(
									GameManager.getInstance().m_user_screen.m_user_resource, head, data);
							GameManager.getInstance().m_user_screen.m_user_resource.updateResource(head, inst);
							GameManager.getInstance().m_user_screen.logicAnims();
						}
					}
					else {

						// 更新场景中的动态Actor
						if (m_resource_scene.containMissRes(head)) {
							inst = ResourceManager.getInstance().loadResource(m_resource_scene, head, data);
							// System.out.println("m_resource_scene inst=" + inst);
							m_resource_scene.updateResource(head, inst);
						}

						if (m_resource_static.containMissRes(head)) {
							inst = ResourceManager.getInstance().loadResource(m_resource_static, head, data);
							// System.out.println("m_resource_static inst=" + inst);
							m_resource_static.updateResource(head, inst);

						}

						// 更新场景中的动态Actor
						if (m_scene != null) {
							inst = ResourceManager.getInstance().loadResource(m_resource_scene, head, data);
							for (int j = 0; j < m_scene.m_dynamic_actors.size(); j++) {
								((Actor) (m_scene.m_dynamic_actors.elementAt(j))).updateComponent(head, inst);
							}
						}
						else {
							if (head.m_type == ObjectAdapter.RESOURCE_TYPE_SCENE) {
								GameManager.getInstance().m_scene = (GameScene) ResourceManager.getInstance()
										.loadResource(
												GameManager.getInstance().m_resource_scene, head, data);
							}
						}

					}

				}
				catch (Exception e) {
					Tools.debug(e);
				}

			}
			bais.close();
			dis.close();
		}
		catch (IOException ex) {
			if (body != null) {
				for (int i = 0; i < body.length; i++) {
					Tools.debugPrintln("body[" + i + "]=" + body[i]);
				}
			}
			Tools.debug(ex);
		}
	}

	// //资源相关
	// ////////////////////////////////////////////////////////////////////

	public void connectionTimeout()
	{
	}

	public void connectionCreated()
	{
	}

	public void connectionBroken()
	{
	}

	private int m_connectionIdle = 0; // 用于保持心跳的帧计数
	private int m_keepAliveInterval = 300; // 心跳间隔

	/**
	 * 设置心跳间隔
	 *
	 * @param n
	 */
	public void setKeepAliveInterval(int n)
	{
		m_keepAliveInterval = n;
	}

	// 每次发消息都需要将_connectionIdle重置
	public void resetConnectionIdle()
	{
		m_connectionIdle = 0;
	}

	/**
	 * 保持连接（定时发心跳）
	 *
	 * @return
	 */
	public boolean keepConnectionAlive()
	{
		if (m_connection != null) {
			if (m_connectionIdle > 0) {
				m_connectionIdle--;
			}
			else {
				m_connection.keepAlive();
				//#if edition == "DEBUG"
				//# m_connection.delaysTime();
				//#endif
				m_connectionIdle = m_keepAliveInterval;
			}
			return true;
		}
		return false;
	}

	/**
	 * 获得连接
	 *
	 * @return
	 */
	public final BaseConnection getConnection()
	{
		return m_connection;
	}

	// /**
	// * 创建连接
	// * @param receiver
	// * @throws Exception
	// */
	// public void createConnection(ConnectionHandler receiver) throws Exception
	// {
	// if (_server_type) {
	// m_connection = BaseConnection.createConnection(
	// BaseConnection.CONNECTION_TYPE_HTTP,
	// SERVER_URL,
	// SERVER_PORT,
	// receiver);
	// }
	// else {
	// m_connection = BaseConnection.createConnection(
	// BaseConnection.CONNECTION_TYPE_TCP,
	// SERVER_URL,
	// SERVER_PORT,
	// receiver);
	// }
	// }

	public void closeConnection()
	{
		if (m_connection != null)
			m_connection.close();
	}

	public void clearConnection()
	{
		m_connection = null;
	}

	/**
	 * 创建连接 默认GameManager为子类
	 *
	 * @param receiver
	 * @throws Exception
	 */
	public void createConnection(String serverURL, int serverPort) throws Exception
	{
		//如果没有IP存档，存档
//		if(!Tools.haveRecord(GameMIDlet.m_iprecord) ){
//			HttpConnect.saveAddress(SERVER_URL, SERVER_PORT);
//		}
		BaseConnection.s_recvPackageId = -1;
		if (_server_type) {
			m_connection = BaseConnection.createConnection(BaseConnection.CONNECTION_TYPE_HTTP, serverURL, serverPort,
					s_instance);
		}
		else {
			m_connection = BaseConnection.createConnection(BaseConnection.CONNECTION_TYPE_TCP, serverURL, serverPort,
					s_instance);
		}
	}

	protected BaseConnection m_connection; // 连接

	// private static final boolean HTTP_SERVER = true; // http连接方式
	private static final boolean TCP_SERVER = false; // tcp连接方式

	// 连接方式
	public static boolean _server_type = TCP_SERVER;

	// public static String SERVER_URL = "192.2.9.12";//小灰灰
	// public static String SERVER_URL = "192.2.9.89";//童
	// public static String SERVER_URL = "127.0.0.1";//本地
	// public static String SERVER_URL = "192.2.9.191";// 繁鹏
	// public static String SERVER_URL = "106.3.241.131";// 外网
	//重要
	public static final String SERVER_URL = HttpConnect.HOST2;//"211.151.33.73";// 外网211.151.33.72,3,211.151.33.73
	public static final int SERVER_PORT = HttpConnect.SERVER_PORT;//23590;
//	public static String SERVER_URL = "211.151.33.72";
//	public static int SERVER_PORT = 23591;
	// public static String SERVER_URL = "192.2.8.161";//小颖颖
	// public static int SERVER_PORT = 12345;
	// public static int SERVER_PORT = 1928;
//	 public static int SERVER_PORT = 7878;

	// public static int SERVER_PORT = 2819;
	// public static int SERVER_PORT = 2302;
	// public static int SERVER_PORT = 2888;

	// //
	// ////////////////////////
	/*
	 * public static final String[] LOADING_TIPS = { // "战斗开始后，系统会自动帮你连续释放技能",
	 * // "点击任务目标中的npc链接，就可以开始自动寻路", // "按下确定键，会自动选中距离你最近的npc",
	 * "背包只有一个，但是会按照装备、消耗、材料、任务、其他分成五类", "在右上角的小地图中，玩家为白色，NPC为黄色，怪物为红色",
	 * "掉落在地图上的装备道具，只要走近，就会自动捡拾到背包中", "有些互动任务需要进行不止一次互动操作",
	 * "宝石有红黄蓝绿四种颜色。每种宝石只能镶嵌到对应颜色的插槽之中", "你可以毫无损伤的将镶嵌的宝石取下，当然，得出点小钱",
	 * "三块同样的宝石就可以合成更高一级的宝石", "只要完成每日的活动任务，就可以得到银票", "加入家族之后就可以每天免费得到宝石" };
	 */

	public static final String[] LOADING_TIPS = {"背包只有一个，但可按装备、消耗、材料、其他分类显示",
			"怪物掉落的装备及道具，只要走近，就会被自动捡拾到背包中", "宝石有红黄蓝绿四种颜色，只能镶嵌到对应颜色的插槽之中",
			"可以使用提取道具，将镶嵌的宝石逐一取下。如果选择一次全部取下来，会毁掉原先的装备", "三块同样的宝石就可以合成更高一级的宝石",
			"加入家族就可以使用贡献值每日抽奖，随着家族级别越高，抽奖机会会增多，得到的奖励也会越来越好",
			"参加战场的每日活动可以取得战功，使用战功可以在战功商店购买物资", "装备强化在+3段以前，不会失败", "装备强化在+4段以后，会有一定几率失败，失败的话将会降低装备的强化段数",
			"装备强化在+12段以后，属性会得到飞跃性提升，但是强化失败的话，装备会被毁坏掉，不过可以使用保护符",
			"拍卖是个好地方，可以买到超值物品和出售道具。",
			"当你不知道自己该如何继续游戏时，系统界面中的攻略会给您指引。"};

	public static final String[] LOADING_1_6_LEVEL = { "点击任务目标中的NPC链接，就开始自动寻路", "可以在主菜单的“任务”选项中看到目前所有任务",
			"右上角的小地图中，玩家为白色，NPC为黄色，怪物为红色，传送门为蓝色" };

	public static final String[] LOADING_7_18_LEVEL = { "右上角的小地图中，玩家为白色，NPC为黄色，怪物为红色", "有些任务需要进行多次的互动操作才能完成",
			"只有好友才能为你的摇钱树浇水，摇钱树每天可以收获一次，收获的银票非常有用", "善用“连招”，可以让战斗变得更为轻松",
			"达到18级后，玩家就可以进行转职，转职后不仅可学习更多的战斗技能，还可以获得额外的属性提升", "为家族捐赠生活材料可以获得贡献值，家族则获得经验值" };

	public static final String[] LOADING_19_30_LEVEL = { "有些任务需要进行多次的互动操作才能完成", "只有好友才能为你的摇钱树浇水，摇钱树每天可以收获一次，收获的银票非常有用",
			"善用“连招”，可以让战斗变得更为轻松",
			"达到18级后，玩家就可以进行转职，转职后不仅可学习更多的战斗技能，还可以获得额外的属性提升", "为家族捐赠生活材料可以获得贡献值，家族则获得经验值", "每天有10次每日任务机会，提供大量的升级经验值",
			"家族达到升级人数及约定经验值后就会自动升级" };

	public static final String[] LOADING_30_40_LEVEL = { "每天有10次每日任务机会，提供大量的升级经验值", "杀死你的非同门派玩家会自动成为你的/”仇敌/”",
			"家族达到升级人数及约定经验值后就会自动升级" };

	public static final String[] LOADING_40_50_LEVEL = { "杀死你的非同门派玩家会自动成为你的/”仇敌/”" };

	private final static String[] LOADING_DESCRIBE = { "正在释放资源...", "正在加载人物信息...", "正在加载场景资源...", "正在初始化场景...", };

	public String[] mergeStrings()
	{
		if (m_role == null) {
			return LOADING_TIPS;
		}
		String[] beginString;
		if (m_role.m_lv >= 1 && m_role.m_lv <= 6) {
			beginString = LOADING_1_6_LEVEL;
		}
		else if (m_role.m_lv >= 7 && m_role.m_lv <= 18) {
			beginString = LOADING_7_18_LEVEL;
		}
		else if (m_role.m_lv >= 19 && m_role.m_lv <= 30) {
			beginString = LOADING_19_30_LEVEL;
		}
		else if (m_role.m_lv >= 30 && m_role.m_lv <= 40) {
			beginString = LOADING_30_40_LEVEL;
		}
		else if (m_role.m_lv >= 40 && m_role.m_lv <= 50) {
			beginString = LOADING_40_50_LEVEL;
		}
		else {
			return LOADING_TIPS;
		}
		int beginSize = beginString.length;
		int LoadTipSize = LOADING_TIPS.length;
		int size = beginSize + LoadTipSize;
		String[] temp = new String[size];
		for (int i = 0; i < beginSize; i++) {
			temp[i] = beginString[i];
		}
		for (int j = 0; j < LoadTipSize; j++) {
			temp[beginSize + j] = LOADING_TIPS[j];
		}
		return temp;
	}

	public boolean m_isInTeach;//是否在教学状态
	public String[][] m_desc_teach;//教学提示
	public int[][] m_infos_teach;//教学提示所需参数
	public int[][] m_keys_teach;//教学提示确认的按键
	public int[][] m_keys_skip_teach;//教学提示跳过的按键
	public byte[] m_types_teach;//教学提示跳过的按键
	public int m_index_teach;

	/**
	 * 脱离教学
	 */
	public void getOutOfTeach()
	{
		m_isInTeach = false;
		m_desc_teach = null;
		m_infos_teach = null;
		m_keys_teach = null;
		m_keys_skip_teach = null;
		m_types_teach = null ;
		m_index_teach = 0;
	}
}
